LeetCode刷题338. Counting Bits

题目描述:

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.

Example 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [0,1,1,2,1,2]
 

题目大意:计算0-num中每个数所对应的二进制中1的个数

解题思路:简单粗暴,利用Java已有的API直接解决

class Solution {
    public int[] countBits(int num) {
        int[] arr = new int[num+1];
        for(int i=0;i<num+1;i++){
            arr[i] = Integer.bitCount(i);
        }
        return arr;
    }
}

猜你喜欢

转载自blog.csdn.net/u014116780/article/details/82950202