Skip to content

Commit 17c9aa7

Browse files
committed
LC#338 returns array containting bit counts, O(NlogN) time, O(N) Space
1 parent 48eb817 commit 17c9aa7

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Leetcode/easy/CountingBits338.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package easy;
2+
3+
import java.util.Arrays;
4+
5+
public class CountingBits338 {
6+
7+
public static int[] countBits(int n) {
8+
int[] ans = new int[n + 1];
9+
10+
for (int i = 0; i <= n; i++) {
11+
ans[i] = countBinaryOnes(i);
12+
}
13+
return ans;
14+
}
15+
16+
private static int countBinaryOnes(int num) {
17+
int count = 0;
18+
int mask = 1;
19+
20+
while (num != 0) {
21+
if ((num & mask) != 0)
22+
count++;
23+
24+
num = num >> 1; // right shift
25+
}
26+
return count;
27+
}
28+
29+
public static void main(String[] args) {
30+
System.out.println(Arrays.toString(countBits(2)));
31+
System.out.println(Arrays.toString(countBits(5)));
32+
System.out.println(Arrays.toString(countBits(0)));
33+
}
34+
}
35+
36+
/* output:
37+
[0, 1, 1]
38+
[0, 1, 1, 2, 1, 2]
39+
[0]
40+
*/

0 commit comments

Comments
 (0)