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
Copy file name to clipboardExpand all lines: src/main/java/com/fishercoder/solutions/_338.java
+8-27Lines changed: 8 additions & 27 deletions
Original file line number
Diff line number
Diff line change
@@ -1,26 +1,5 @@
1
1
packagecom.fishercoder.solutions;
2
2
3
-
/**338. Counting Bits
4
-
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.
5
-
6
-
Example:
7
-
For num = 5 you should return [0,1,1,2,1,2].
8
-
9
-
Follow up:
10
-
11
-
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
12
-
Space complexity should be O(n).
13
-
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
14
-
15
-
Hint:
16
-
17
-
You should make use of what you have produced already.
18
-
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
19
-
Or does the odd/even status of the number help you in calculating the number of 1s?
20
-
21
-
*
22
-
*
23
-
*/
24
3
publicclass_338 {
25
4
publicstaticclassSolution1 {
26
5
//use the most regular method to get it AC'ed first
@@ -43,12 +22,14 @@ private int countOnes(int i) {
43
22
}
44
23
45
24
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
49
-
right shift by 1 means to divide by 2
50
-
AND with 1 means to modulo 2
51
-
this is so cool!*/
25
+
/**
26
+
* lixx2100's post is cool:https://discuss.leetcode.com/topic/40162/three-line-java-solution
27
+
* An easy recurrence for this problem is f[i] = f[i / 2] + i % 2
28
+
* and then we'll use bit manipulation to express the above recursion function
0 commit comments