File tree Expand file tree Collapse file tree 1 file changed +16
-2
lines changed Expand file tree Collapse file tree 1 file changed +16
-2
lines changed Original file line number Diff line number Diff line change @@ -27,7 +27,21 @@ Space complexity should be O(n).
27
27
*
28
28
*/
29
29
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
+ }
31
45
32
46
33
47
//use the most regular method to get it AC'ed first
@@ -50,7 +64,7 @@ private int countOnes(int i) {
50
64
51
65
public static void main (String ...strings ){
52
66
CountingBits test = new CountingBits ();
53
- int num = 5 ;
67
+ int num = 15 ;
54
68
int [] ones = test .countBits (num );
55
69
CommonUtils .printArray (ones );
56
70
}
You can’t perform that action at this time.
0 commit comments