Last active
September 18, 2016 12:10
-
-
Save rajeakshay/a34bf60781736900327c11984a3b718b to your computer and use it in GitHub Desktop.
LeetCode 338. Counting Bits - Counting number of set bits in all numbers from 0 to num (Problem: https://leetcode.com/problems/counting-bits) - Given a non negative integer number num. For every number i in the range 0 ≤ i ≤ num, calculate and store the number of 1's in the binary representation of i and return results as an array. Example: For …
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* LeetCode 338. Counting Bits | |
* Counting number of set bits in all numbers from 0 to num (Problem Link: https://leetcode.com/problems/counting-bits) | |
* Given a non negative integer number num. For every number i in the range 0 ≤ i ≤ num, calculate and store the number of 1's | |
* in the binary representation of i and return results as an array. | |
* Example: For num = 5, program should return [0,1,1,2,1,2]. | |
*/ | |
public class CountingBits { | |
static int countSetBits(int n){ | |
// Trick from K&R | |
int count = 0; | |
while(n != 0){ | |
n &= n-1; | |
count++; | |
} | |
return count; | |
} | |
public int[] countBits(int num) { | |
int[] result = new int[num+1]; | |
result[0] = 0; // No. of set bits in 0 is 0 | |
for(int i=1 ; i <= num; i++){ | |
if((i & (i - 1)) == 0){ | |
// All powers of 2 will have only 1 set bit | |
result[i] = 1; | |
} | |
else{ | |
// Calculate set bits for all others | |
result[i] = countSetBits(i); | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment