-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCountingBits.java
More file actions
35 lines (26 loc) · 950 Bytes
/
Copy pathCountingBits.java
File metadata and controls
35 lines (26 loc) · 950 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num
// calculate the number of 1's in their binary representation and return them as an array.
// See: https://leetcode.com/problems/counting-bits/
package leetcode.dynamic_programming;
import java.util.Arrays;
public class CountingBits {
public int[] countBits(int num) {
int[] res = new int[num + 1];
int pointer = 0;
int pow = 1;
for (int i = 1; i < res.length; i++) {
if (i == pow) {
pow *= 2;
pointer = 0;
}
res[i] = res[pointer] + 1;
pointer++;
}
return res;
}
public static void main(String[] args) {
CountingBits sln = new CountingBits();
System.out.println(Arrays.toString(sln.countBits(2)));
System.out.println(Arrays.toString(sln.countBits(5)));
}
}