Skip to content

Commit 61a3d6b

Browse files
dp approach to counting bits
1 parent e9f54b5 commit 61a3d6b

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

MEDIUM/src/medium/CountingBits.java

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,21 @@ Space complexity should be O(n).
2727
*
2828
*/
2929
public class CountingBits {
30-
//TODO: follow its hint to solve it using DP
30+
private class DP_Solution{
31+
//lixx2100's post is cool:https://discuss.leetcode.com/topic/40162/three-line-java-solution
32+
//An easy recurrence for this problem is f[i] = f[i / 2] + i % 2
33+
//and then we'll use bit manipulation to express the above recursion function
34+
// right shift by 1 means to divide by 2
35+
//AND with 1 means to modulo 2
36+
//this is so cool!
37+
public int[] countBits(int num) {
38+
int[] ones = new int[num+1];
39+
for(int i = 1; i <= num; i++){
40+
ones[i] = ones[i >> 1] + (i&1);
41+
}
42+
return ones;
43+
}
44+
}
3145

3246

3347
//use the most regular method to get it AC'ed first
@@ -50,7 +64,7 @@ private int countOnes(int i) {
5064

5165
public static void main(String...strings){
5266
CountingBits test = new CountingBits();
53-
int num = 5;
67+
int num = 15;
5468
int[] ones = test.countBits(num);
5569
CommonUtils.printArray(ones);
5670
}

0 commit comments

Comments
 (0)