leetCode 338

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetCode 338相关的知识,希望对你有一定的参考价值。

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.

 

思路:数字总比[数字二进制最高位置0后的数字]的多一个1

 

public static int[] countBits(int num) {
        int len = num + 1;
        int[] res = new int[len];
        res[0] = 0;
        
        for (int i = 1; i < len; i++) {
            res[i] = res[Util.highBit(i)] + 1;
        }
        return res;
    }

//将二进制的最高位置0
    public static int highBit(int x) {
        return x - (int) Math.pow(2, (int) (Math.log(x) / Math.log(2)));
    }

 

以上是关于leetCode 338的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode_338_CountingBits

leetcode338

leetCode 338

LeetCode338. Counting Bits (2 solutions)

[leetcode-338-Counting Bits]

leetcode 338