File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Leetcode/DailyChallenges/March2022 Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ package LeetcodeDaily .March2022 ;
2+
3+ import java .util .Arrays ;
4+
5+ public class Day1CountingBitsLC338 {
6+
7+ // O(N) time | O(N) space
8+ public static int [] countBits (int n ) {
9+
10+ int [] countOfOnes = new int [n + 1 ];
11+ countOfOnes [0 ] = 0 ;
12+
13+ for (int i = 1 ; i <= n ; i ++) {
14+
15+ if (i % 2 == 0 ) {
16+ // for even number, LSB will be zero, so doing right shift of number by 1 bit
17+ // will not lose set one bit(1)
18+ countOfOnes [i ] = countOfOnes [i / 2 ];
19+ } else {
20+ // for odd number, LSB will always be one, so doing right shift of number by 1
21+ // bit will also lose 1 bit
22+ countOfOnes [i ] = 1 + countOfOnes [i / 2 ];
23+ }
24+ }
25+
26+ return countOfOnes ;
27+ }
28+
29+ public static void main (String [] args ) {
30+ System .out .println (Arrays .toString (countBits (15 )));
31+ }
32+
33+ }
You can’t perform that action at this time.
0 commit comments