338. Counting Bits

来源:互联网 发布:上海房价数据库 编辑:程序博客网 时间:2024/05/29 02:47

338. Counting Bits

计算零到一个数之间所有数的二进制中1的个数。

class Solution {public:vector<int> countBits(int num) {vector<int> ans;ans.clear();for (int i = 0; i <= num; i++){int now = i;int flag = 0;while (now){if (now % 2) flag++;now = now >> 1;}ans.push_back(flag);}return ans;}};
很简单的想法,每个数都转为二进制,然后算1个数,很暴力,很慢。
class Solution {public:vector<int> countBits(int num) {vector<int> bits(num + 1, 0);for (int i = 1; i <= num; i++) bits[i] += bits[i & (i - 1)] + 1;return bits;}};
很神奇的想法,num数中1的个数从num&(num-1)+1转移过来,节约了很多时间,很棒!

奇数

//10011---------num--------------------3
//10010---------num-1-----------------2
//10010---------num&(num-1)-------2

偶数
//10010--------num--------------------2
//10001--------num--------------------2
//10000--------num--------------------1


原创粉丝点击