338. Counting Bits

来源:互联网 发布:网络分销系统发展趋势 编辑:程序博客网 时间:2024/05/20 18:00

iven 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:

For num = 5 you should return [0,1,1,2,1,2].

由以前求i的二进制中1的个数方法得知,i的二进制比i&(i-1)多一个

class Solution {public:vector<int> countBits(int num) {vector<int> res(num + 1);res[0] = 0;for (int i = 1; i <= num; i++){res[i] = res[i&(i - 1)] + 1;}return res;}};


0 0
原创粉丝点击