Number of 1 Bits
来源:互联网 发布:淘宝账户永久无法注销 编辑:程序博客网 时间:2024/06/05 22:32
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.
Bit Manipulation
思路很简单:(4ms)
int hammingWeight(uint32_t n) { int count = 0;while (n){if (n % 2)count++;n /= 2;}return count; }思路:(4ms)
位运算
int hammingWeight(uint32_t n) { int count = 0;while (n){if (n & 1)count++;<span style="white-space:pre"></span>//count += n & 0x1;n = n >> 1;//n >>= 1;}return count; }思路:(8ms)
位运算的扩展;
容易想到的是不管是多少个1,都要循环执行32次;
巧妙解法:将循环次数减少到与1的个数相同。利用的性质就是本身n相与n-1。
int hammingWeight(uint32_t n) { <span style="white-space:pre"></span>int count = 0;while (n){n = n & (n - 1);count++;}return count; }总结:最后一种解法效率反而更低。
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
- eclipse+webservice开发实例【开发环境jdk1.7.0_67+eclipse-jee-luna+tomcat6.0.30+axis2-1.6.1(此为webservice的jar包)】
- POJ 2752 Seek the Name, Seek the Fame(kmp)
- 安装R package的2种方法
- 14 个 Linux grep 命令的例子
- 贝塞尔曲线
- Number of 1 Bits
- 黑马程序员-----------ios培训 oc内存管理(一)
- OC 使用 “消息结构”
- 【ThinkingInJava】45、用java标准库里面的静态函数调用,复制数组
- 破解TexturePacker加密资源 —— 使用IDA
- 【ThinkingInJava】46、把数组反序排列
- ubuntu清除多余内核
- C++获取文本文件字节数的一个小方法
- 安卓学习笔记——ActionBar的使用