|
| 1 | +package medium; |
| 2 | + |
| 3 | +import utils.CommonUtils; |
| 4 | + |
| 5 | +/**338. Counting Bits QuestionEditorial Solution My Submissions |
| 6 | +Total Accepted: 37328 |
| 7 | +Total Submissions: 64455 |
| 8 | +Difficulty: Medium |
| 9 | +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. |
| 10 | +
|
| 11 | +Example: |
| 12 | +For num = 5 you should return [0,1,1,2,1,2]. |
| 13 | +
|
| 14 | +Follow up: |
| 15 | +
|
| 16 | +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? |
| 17 | +Space complexity should be O(n). |
| 18 | +Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. |
| 19 | +
|
| 20 | +Hint: |
| 21 | +
|
| 22 | +You should make use of what you have produced already. |
| 23 | +Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. |
| 24 | +Or does the odd/even status of the number help you in calculating the number of 1s? |
| 25 | +
|
| 26 | +* |
| 27 | +* |
| 28 | +*/ |
| 29 | +public class CountingBits { |
| 30 | + //TODO: follow its hint to solve it using DP |
| 31 | + |
| 32 | + |
| 33 | + //use the most regular method to get it AC'ed first |
| 34 | + public int[] countBits(int num) { |
| 35 | + int[] ones = new int[num+1]; |
| 36 | + for(int i = 0; i <= num; i++){ |
| 37 | + ones[i] = countOnes(i); |
| 38 | + } |
| 39 | + return ones; |
| 40 | + } |
| 41 | + |
| 42 | + private int countOnes(int i) { |
| 43 | + int ones = 0; |
| 44 | + while(i != 0){ |
| 45 | + ones++; |
| 46 | + i &= (i-1); |
| 47 | + } |
| 48 | + return ones; |
| 49 | + } |
| 50 | + |
| 51 | + public static void main(String...strings){ |
| 52 | + CountingBits test = new CountingBits(); |
| 53 | + int num = 5; |
| 54 | + int[] ones = test.countBits(num); |
| 55 | + CommonUtils.printArray(ones); |
| 56 | + } |
| 57 | +} |
0 commit comments