zoukankan      html  css  js  c++  java
  • [LeetCode]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].

    这应该是一道新放入的题。意思是给你一个非负整数num,对于0到num这(num+1)个整数,求出每个数用二进制表示时1的个数。

    最简单的思路:对每个数,利用移位和按位与(i & 1)运算,计算1的个数。这样时间复杂度为O(n*sizeof(integer)),如果int用32位表示,那么时间复杂度就是O(32n)。

    考虑优化成O(n):

    对于11这个数,我们暂时用一个字节来表示

    11:           0000 1011

    11/2 = 5:0000 0101

    容易发现,除了11最右边那个位和5的最高位,其他位对应一样。也就是说i用二进制表示时1出现的次数等于i/2中1出现的次数加1(如果i用二进制表示时最右边一位为1,否则不加1)。这样我们在计算i时可以利用前面已计算出的i/2:ret[i] = ret[i/2] + (i % 2 == 0 ? 0 : 1);

    AC代码(C++):

    class Solution {
    public:
        vector<int> countBits(int num) {
            if (num <= 0)
                return vector<int>(1, 0);
    
            vector<int> ret(num+1, 0);
            int i = 0;
            int half = 0;
    
            for (i = 1; i <= num; ++i)
            {
                //the number of 1's in half equals the number of 1's in i except the right-most bit in i 
                half = i >> 1;
                if (i % 2 == 0)//the right-most bit in i is 0
                    ret[i] = ret[half];
                else//the right-most bit in i is 1
                    ret[i] = ret[half] + 1;
            }
    
            return ret;
        }
    };
  • 相关阅读:
    巡风安装笔记
    泛微ecology OA系统某接口存在数据库配置信息泄露漏洞
    Apache Solr Velocity模板远程代码执行复现
    泛微OA系统多版本存在命令执行漏洞
    各种浏览器UA值
    使用python合并excel
    疑难杂症----udf提权无法导出.dll
    疑难杂症----windows7
    Nmap的使用
    Sqlmap的使用
  • 原文地址:https://www.cnblogs.com/vdvvdd/p/5291714.html
Copyright © 2011-2022 走看看