zoukankan      html  css  js  c++  java
  • LeetCode 191 Number of 1 Bits

    Problem:

    Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

    For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

    Summary:

    求三十二位无符号数含1的位数。

    Analysis:

    1. 最简单的思路为将n移位直至n为0,每移位一次判断最低位是否为1。但若有1在最高位则需移位32次,效率太低。

     1 class Solution {
     2 public:
     3     int hammingWeight(uint32_t n) {
     4         int cnt = 0;
     5         while (n) {
     6             cnt += n & 1;
     7             n = n >> 1;
     8         }
     9         
    10         return cnt;
    11     }
    12 };

    2. 下面这种思路能够把移位的次数降低至与含1的位数相等,大大提高了效率。

    举个栗子:若n = 1010010,则:

    1. n = 1010010  n - 1 = 1010001  n & (n - 1) = 1010000
    2. n = 1010000  n - 1 = 1001111  n & (n - 1) = 1000000
    3. n = 1000000  n - 1 = 0111111  n & (n - 1) = 0000000

    可以看出,每进行一次n & (n - 1)操作,最低位上的1就会被消去。

     1 class Solution {
     2 public:
     3     int hammingWeight(uint32_t n) {
     4         int cnt = 0;
     5         while (n) {
     6             n &= (n - 1);
     7             cnt++;
     8         }
     9         
    10         return cnt;
    11     }
    12 };
  • 相关阅读:
    python3监控网站状态
    暴力屏蔽80访问失败的用户
    python3爬取中国药学科学数据
    python3发邮件脚本
    OOP AOP
    lambda
    jni
    Gradle史上最详细解析
    supersocket 遇到的Failed to initialize 和 log4net用法
    在c#中利用keep-alive处理socket网络异常断开的方法
  • 原文地址:https://www.cnblogs.com/VickyWang/p/6032402.html
Copyright © 2011-2022 走看看