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].
代碼如下:
1 public class Solution {
2 public int[] countBits(int n) {
3 int[] a=new int[n+1];
4
5 for(int i=0;i<=n;i++)
6 {
7 String s=Integer.toBinaryString(i);
8 char[] ss=s.toCharArray();
9 int count=0;
10 for(int j=0;j<ss.length;j++)
11 {
12 if(ss[j]=='1')
13 count++;
14 }
15 a[i]=count;
16 }
17 return a;
18 }
19 }