比特位计数

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

示例阐明请见LeetCode官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:库函数

偷懒的我间接用了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);        }    }}
【每日寄语】 很多时候,颠倒一下视角,会发现一个全新的世界。