1. 程式人生 > >LeetCode刷題338. Counting Bits

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;
    }
}