You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
7
5
@@ -24,45 +22,39 @@ Space complexity should be O(n).
24
22
*
25
23
*/
26
24
publicclass_338 {
27
-
privateclassDPSolution {
28
-
//lixx2100's post is cool:https://discuss.leetcode.com/topic/40162/three-line-java-solution
29
-
//An easy recurrence for this problem is f[i] = f[i / 2] + i % 2
30
-
//and then we'll use bit manipulation to express the above recursion function
31
-
// right shift by 1 means to divide by 2
32
-
//AND with 1 means to modulo 2
33
-
//this is so cool!
25
+
publicstaticclassSolution1 {
26
+
//use the most regular method to get it AC'ed first
34
27
publicint[] countBits(intnum) {
35
28
int[] ones = newint[num + 1];
36
-
for (inti = 1; i <= num; i++) {
37
-
ones[i] = ones[i >> 1] + (i & 1);
29
+
for (inti = 0; i <= num; i++) {
30
+
ones[i] = countOnes(i);
38
31
}
39
32
returnones;
40
33
}
41
-
}
42
34
43
-
44
-
//use the most regular method to get it AC'ed first
45
-
publicint[] countBits(intnum) {
46
-
int[] ones = newint[num + 1];
47
-
for (inti = 0; i <= num; i++) {
48
-
ones[i] = countOnes(i);
35
+
privateintcountOnes(inti) {
36
+
intones = 0;
37
+
while (i != 0) {
38
+
ones++;
39
+
i &= (i - 1);
40
+
}
41
+
returnones;
49
42
}
50
-
returnones;
51
43
}
52
44
53
-
privateintcountOnes(inti) {
54
-
intones = 0;
55
-
while (i != 0) {
56
-
ones++;
57
-
i &= (i - 1);
45
+
privateclassSolution2 {
46
+
/**lixx2100's post is cool:https://discuss.leetcode.com/topic/40162/three-line-java-solution
47
+
An easy recurrence for this problem is f[i] = f[i / 2] + i % 2
48
+
and then we'll use bit manipulation to express the above recursion function
0 commit comments