leetcode-338. Counting Bits

来源:互联网 发布:神硕微信免费推广软件 编辑:程序博客网 时间:2024/04/16 21:52

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:
For num = 5 you should return [0,1,1,2,1,2].

思路:从小到大遍历,当前数字的bit1的个数是他右移一位对应的数的bit1个数加上最后一位是否为1

class Solution {public:    vector<int> countBits(int num) {       //思路:i中bit1的个数等于 i>>1 1的个数加 i&0x01;       if(num < 0)       {           vector<int> result(1,0);           return result;       }       vector<int> result(num+1,0);       for(int i=1;i<=num;i++)       {           result[i] = result[i>>1] + (i&0x01);       }       return result;    }};
0 0