338. Counting Bits

来源:互联网 发布:网络大电影票房排行榜 编辑:程序博客网 时间:2024/05/16 01:27

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

第一种方法很直接,本来以为不会通过的,结果直接ac了

public class Solution {    public int[] countBits(int num) {    int[] res=new int[num+1];    int j=0,n=0;        for(int i=0;i<=num;i++){        n=i;        for(j=0;n>0;j++){        n&=(n-1);        }        res[i]=j;        }        return res;    }}

第二种是discuss里的方法,在增加一位的情况下,不断的将之前的结果加1.

public class Solution {    public int[] countBits(int num) {    int[] res=new int[num+1];    res[0]=0;    int i,pow=1,t;        for(i=1,t=0;i<=num;i++,t++){        if(i==pow){        pow*=2;        t=0;        }        res[i]=res[t]+1;        }        return res;    }}


0 0