分类: Java
2016-03-31 21:14:34
iven 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:
package leetcode_338;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int tmp = sc.nextInt();
Solution a =new Solution();
int array[]=a.countBits(tmp);
// for(int i=0;i
// System.out.println(array[i]);
// }
System.out.println(Arrays.toString(array));
}
}
package leetcode_338;
public class Solution {
public int[] countBits(int num) {
int a[] = new int[num +1];
a[0] = 0;
for (int i = 1; i < num + 1; i++) {
int x =i;
int count=0;
while(x !=0){
if((x&1) == 1) count++;
x =x>>1;
}
a[i]=count;
}
return a;
}
}