头图

Bit count

Title description: Given a non-negative integer num . For i in the range 0 ≤ i ≤ num , calculate the number of 1s in its binary number and return them as an array.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/counting-bits/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution one: library function

Being lazy, I directly used the java library function Integer.bitCount solve this problem. Despise yourself

Tip: can use dynamic programming to achieve a more efficient solution.

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);
        }
    }
}
[Daily Message] Many times, if you reverse your perspective, you will find a whole new world.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!