LeetCode0338-计算数字对应二进制中1的数目

//给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。

//方法一:对于所有的数字,只有两类:
//
//奇数:二进制表示中,奇数一定比前面那个偶数多一个 1,因为多的就是最低位的 1。
//偶数:二进制表示中,偶数中 1 的个数一定和除以 2 之后的那个数一样多。因为最低位是 0,除以 2 就是右移一位,也就是把那个 0 抹掉而已,所以 1 的个数是不变的。
//
//作者:duadua
//链接:https://leetcode-cn.com/problems/counting-bits/solution/hen-qing-xi-de-si-lu-by-duadua/
//来源:力扣(LeetCode)
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
public class Num338_countBits {

    public static int[] countBits(int n) {

        int[] result = new int[n+1];
        result[0]=0;
        for (int i =1;i<n+1;i++){

            if(i%2==0){
                result[i]=result[i/2];
            }
            if(i%2!=0){
                result[i]=result[i-1]+1;

            }

        }
        return result;
    }

    //方法二:java的Integer有自带的方法Integer.bitCount,可以统计出每个数字对应二进制中1的个数
    public static int[] countBits2(int n){
        int[] result = new int[n+1];
        for(int i=0;i<n+1;i++){
            result[i]= Integer.bitCount(i);
            System.out.println(result[i]);
        }
        return result;
    }


    public static void main(String[] args) {
        int n =2;
        countBits(2);
        countBits2(5);

    }
}

 

posted on 2021-06-30 10:41  cStream  阅读(120)  评论(0)    收藏  举报