Skip to content

Commit 37c1a84

Browse files
refactor 338
1 parent 84e901a commit 37c1a84

File tree

1 file changed

+8
-27
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+8
-27
lines changed

src/main/java/com/fishercoder/solutions/_338.java

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,5 @@
11
package com.fishercoder.solutions;
22

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-
*/
243
public class _338 {
254
public static class Solution1 {
265
//use the most regular method to get it AC'ed first
@@ -43,12 +22,14 @@ private int countOnes(int i) {
4322
}
4423

4524
private class Solution2 {
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
29+
* right shift by 1 means to divide by 2
30+
* AND with 1 means to modulo 2
31+
* this is so cool!
32+
*/
5233
public int[] countBits(int num) {
5334
int[] ones = new int[num + 1];
5435
for (int i = 1; i <= num; i++) {

0 commit comments

Comments
 (0)