LeetCode-338-比特位计数

比特位计数

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

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/counting-bits/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:库函数

偷懒的我直接用了java的库函数Integer.bitCount解决了这道题。 自我鄙视一下

提示:可以用动态规划实现更高效的解法。

public class LeetCode_338 {
    /**
     * 使用库函数 Integer.bitCount 直接获取整数对应的二进制的1的个数
     *
     * @param n
     * @return
     */
    public static int[] countBits(int n) {
        int[] result = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            result[i] = Integer.bitCount(i);
        }
        return result;
    }

    public static void main(String[] args) {
        for (int i : countBits(100)) {
            System.out.println(i);
        }
    }
}

【每日寄语】 很多时候,颠倒一下视角,会发现一个全新的世界。

原文地址:https://www.cnblogs.com/kaesar/p/15307021.html