美文网首页
LeetCode #338: Counting Bits

LeetCode #338: Counting Bits

作者: Branch | 来源:发表于2017-05-10 16:04 被阅读0次

Problem

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

*Follow up: **
It is very easy to come up with a solution with run time O(n
sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

Solution

题意

任意给一个数字n,要求算出0,...,n每个数字的二进制表示中一的个数,结果存储在一个vector里。

分析

  1. 这道题一个时间复杂度为O(n*sizeof(int))的解法在另一道题——LeetCode #461: Hamming Distance——里也出现过,即,对数字i进行二进制移位操作,每次右移一位,然后与1求与,如果结果为1,则表示移位后的数字最低有效位为1。重复该操作,直到遍历i的所有二进制位(即循环的条件是i == 0)。
  2. //TODO

Code - Version1

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> result;
        for (int i = 0; i <= num; i++){    //遍历0到num的所有数字
            int count = 0;
            for (int j = i; j; j >>= 1){    //遍历i的所有二进制位
                if (j & 1)    //j&1的结果为1则表示j的最低位为1,否则为0
                    count ++;
            }
            result.push_back(count);
        }
        return result;
    }
};

Code - Version2

//TODO

相关文章

网友评论

      本文标题:LeetCode #338: Counting Bits

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