Number of 1 Bits
来源:互联网 发布:sql nvl函数 编辑:程序博客网 时间:2024/06/14 04:30
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.
目的是判断一个数字的二进制中有点多少个1,
我们可以通过数字的二进制右移的性质进行判断,判断数字的最后一位是不是1,如果是则进行相加:
直到数字为0
class Solution {public: int hammingWeight(uint32_t n) { int result=0; int move; while(n!=0){ move=n& 0x1; result=result+move; n=n>>1; } return result; }};
n = 0x110100 n-1 = 0x110011 n&(n - 1) = 0x110000
n = 0x110000 n-1 = 0x101111 n&(n - 1) = 0x100000
n = 0x100000 n-1 = 0x011111 n&(n - 1) = 0x0
看到这里已经得到了一种新的解法,n中本来有3个1,按照此种思路只需要循环3此即可求出最终结果,
n&(n-1)用于求解n中1的个数,每次n&(n-1)就是消去数字末尾中的1,,通过循环我们可以直到数字中有多少个二进制1,、
class Solution {public: int hammingWeight(uint32_t n) { int result=0; while(n!=0){ n=n&(n-1); result++; } return result; }};
0 0
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Linux内核代码风格
- ugui和ngui手写虚拟摇杆功能比较
- 面向对象的思想
- 各种内部排序算法复杂度的比较和排序方法的选择
- 计算机网络(分组交换与电路交换)
- Number of 1 Bits
- $locationChangeStart ,$locationChangeSuccess,$routeChangeStart,$routeChangeSuccess如何使用
- 【PA2014】【BZOJ3727】Zadanie
- hdoj f(n) 2582 (GCD打表&找规律)好题
- 黑马程序员之System、Runtime、Math、Date、Calendar类
- 动态引用APK文件
- Android LocalSocket与Socket 区别
- UVA 11624 两次bfs搞搞
- UITextView 光标定位