338. Counting Bits Java Solutin
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.
Example:
For num = 5
you should return [0,1,1,2,1,2]
.
Follow up:
- 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?
- Space complexity should be O(n).
- Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language
1 public class Solution { 2 public int[] countBits(int num) { 3 int[] result = new int[num+1]; 4 for(int i=0;i<num+1;i++){ 5 int count = 0; 6 int j = i; 7 while(j!=0){ 8 j=j&(j-1); 9 count++; 10 } 11 result[i] = count; 12 } 13 return result; 14 } 15 }
public int[] countBits(int num) {for (int n = 0; n <= num; ++n) { // binaryNum接收转为二进制的数字 String binaryNum = Integer.toBinaryString(n); char[] charArr = binaryNum.toCharArray(); int i = 0; for (int m = 0; m < charArr.length; ++m) { if (charArr[m] == '1') { i++; } } res[n] = i; }return res; }
第二个解法是网上看到,第一个解法根据编程之美书中求一个数中二进制表示中的 1 的位数得来。