LeetCode 338

来源:互联网 发布:dnf提示框源码 编辑:程序博客网 时间:2024/05/22 06:12

LeetCode 338

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].

Solution:

因为是递增,所以可以找res[i] = res[i & (i-1)] + 1的规律

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

改进:

用bitset,count()函数

class Solution {public:    vector<int> countBits(int num) {        vector<int> res(num+1, 0);        for (int i = 1; i < num+1; i++) {            res[i] = bitset<32>(i).count();        }        return res;    }};
原创粉丝点击