美文网首页
Counting Bits

Counting Bits

作者: BLUE_fdf9 | 来源:发表于2018-09-17 09:55 被阅读0次

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

相关文章

网友评论

      本文标题:Counting Bits

      本文链接:https://www.haomeiwen.com/subject/teqknftx.html