Counting Bits
Description
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 1
Input: 2
Output: [0,1,1]
- Example 2
Input: 5
Output: [0,1,1,2,1,2]
Solution
class Solution {
public int[] countBits(int num) {
int []data1=new int[num+1];
for(int i=0;i<=num;i++){
data1[i]=countOne(i);
}
return data1;
}
public int countOne(int n){
int t = 0; //用来记录位数
int bin = 0; //用来记录最后的二进制数
int r = 0; //用来存储余数
int k=0;
while(n != 0){
r = n % 2;
if (r==1)k++;
n = n / 2;
//bin += r * Math().pow(10,t);
t++;
}
return k;}
}