191.Number of 1 Bits
来源:互联网 发布:java线程池控制并发 编辑:程序博客网 时间:2024/05/17 02:41
问题:
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.
我的解答:
class Solution {public: int hammingWeight(uint32_t n) { int count = 0; for (int i = 0; i < 32; i++) { count += n&0x01; n=n >> 1; } return count; }};
解释:拿到这道题很自然就想到通过移位来计算这里面有多少个1。通过32次与0x01提取最右边的数,看是不是1.
看别人的想法是通过与减一位的数来来计算的。如下
int hammingWeight(uint32_t n) { int count = 0; while (n) { n &= (n - 1); count++; } return count;}
解释:
每次n减1,那么原来的n的最右边一个1就变为0,该1右边的所有0变为1.原n与该n-1与了之后,那么最右1及右边的所有位都为0.如
If n = 00101100, then n - 1 = 00101011, so n & (n - 1) = 00101100 & 00101011 = 00101000. Count = 1.
If n = 00101000, then n - 1 = 00100111, so n & (n - 1) = 00101000 & 00100111 = 00100000. Count = 2.
If n = 00100000, then n - 1 = 00011111, so n & (n - 1) = 00100000 & 00011111 = 00000000. Count = 3.
然后循环的次数不用32次,只要循环“1”的个数就够了,因为是判断n是否为0的。n为0即结束
- 191.Number of 1 Bits
- 191.Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191.Number of 1 Bits
- 商业研究(14):出境游和自由行,接机-送机-包车-当地玩乐
- C++中去除字符串中的无效字符,用于加载配置文件
- HDU-ACM2043
- matlab--关机命令与断点命令
- NO.1 上下机-----机房收费
- 191.Number of 1 Bits
- Zoj 3936 Apples and Ideas【水】
- Ubuntu / CentOS Guide to Install OpenCart
- pwnable.kr之flag
- HDU-ACM2044--Fibonacci数列的应用
- 学之者生,用之者死——ACE历史与简评
- java之Set接口
- [OpenCV] -- win7下配置OpenCV的Qt开发环境
- UINavigationController、UITabBarController