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 };

 

转载于:https://www.cnblogs.com/VickyWang/p/6032402.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值