Chinaunix首页 | 论坛 | 博客
  • 博客访问: 82775
  • 博文数量: 20
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 137
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-24 08:12
文章分类

全部博文(20)

文章存档

2016年(6)

2015年(14)

分类: 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:

  • 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.



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;

}

}




阅读(1702) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~