338. Counting Bits

Total Accepted: 7119  Total Submissions: 12947  Difficulty: Medium

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.

Hint:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. Or does the odd/even status of the number help you in calculating the number of 1s?

Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
  Dynamic Programming Bit Manipulation
Show Similar Problems

分析:

直接用stl中的位类来做。

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> result;
        
        for(int i=0;i<= num;i++)
        {
            bitset<32> cntbit(i);
            result.push_back(cntbit.count());//count()函数统计二进制中1的个数
        }
        
        return result;
    }
};

或者:

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> result;
        
        for (int i = 0; i <= num; ++i) 
        {  
            int curnum = i, cnt = 0;  
            while (curnum) 
            {  
                if (curnum&0x0001) //判断对应二进制数中最右边是否为1 
                    ++cnt;  
                curnum = curnum>>1;  //削掉对应二进制数中最右边的1 
            }  
            result.push_back(cnt);  
        }  
        return result;
    }
};


学习别人的算法:动态规划

可以从每个数的最低位开始分析,例如1001001 ,它的二进制1的个数等于100100 总二进制个数 + 1 。

即 f = f/2 + (f 的最低位)

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



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50986178

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

你可能感兴趣的:(LeetCode,算法,技术,面试,回溯法)