leetcode 338. Counting Bits

Posted Dystopia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 338. Counting Bits相关的知识,希望对你有一定的参考价值。

338. Counting Bits

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
  • class Solution {
    
    public:
        vector<int> countBits(int num) {
            vector<int> count_v(num+1,0);
            for(int i = 1; i <= num;i++)
            {
                int x = i;
                int count=0;
                while(x)
                {
                    if((x & 1)==1) count++;
                    x >>= 1;
                }
                count_v[i] = count;
            }
            return count_v;
        }
    
    };

    注意:1.计算二进制中1的个数,难点在于时间复杂度。有三种基本求二进制1个数的方法:

  • (1)定理求解:取余数的方法,最慢。
  • (2)基本法(雾):值和1进行&操作,然后>>算术右移,仍然有两个循环。(即为本道题我的解法)
  • (3)快速法:n和n-1进行&操作,可以消去二进制最右的1,仍然有两个循环。(在191题中的解法)
  • 参考:http://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html

以上是关于leetcode 338. Counting Bits的主要内容,如果未能解决你的问题,请参考以下文章

leetcode [338]Counting Bits

LeetCode 338. Counting Bits

LeetCode338. Counting Bits (2 solutions)

LeetCode 338. Counting Bits

LeetCode 338. Counting Bits

[Leetcode] 338. Counting Bits