Counting Bits

2018-09-17  本文已影响0人  BLUE_fdf9

题目
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.

答案

class Solution {
    public int[] countBits(int num) {
        int[] f = new int[num + 1];
        f[0] = 0;
        
        for(int i = 1; i <= num; i++) {
            int shift2 = i >> 1;
            f[i] = f[shift2] + (i % 2);
        } 
        return f;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读