位运算 | 2453 | An Easy Problem
来源:互联网 发布:keynote是什么软件 编辑:程序博客网 时间:2024/05/23 14:59
《编程之美》中2.1 求二进制数中1的个数,就找到这题来做,1AC,可是代码不够优化,看到discuss中牛人的代码,发现M神博客中的解释。
POJ 2453 An Easy Problem
#include <stdio.h> int main() { int n, x; while (scanf("%d", &n), n) { x = n & -n; printf("%d\n", n + x + (n ^ n + x) / x / 4); } }位运算当中很多应用到了2的n次幂的性质。
n & -n :计算最右边1的位置:2的n次幂的补还是其本身(不带符号)。例如:101000 & 011000 = 001000
n + x :把右侧连续的1变成1000...的形式。例如:1011100 + 100 = 1100000
n ^ (n + x):取新得到的1和连续的1相连。例如:1011100 ^ 1100000 = 0111100
/ x / 4 :右移两位,再右移x位补差的1到最后的位置上
- 位运算 | 2453 | An Easy Problem
- poj2453 an easy problem (位运算)
- PKU 2453 An Easy Problem
- poj 2453 An Easy Problem
- poj 2453 An Easy Problem
- POJ_2453_An Easy Problem(位运算神代码)
- POJ 1152 An Easy Problem! (取模运算性质)
- POJ 2453 An Easy Problem G++
- An Easy Problem
- 2055 An easy problem
- An Easy Problem!
- An Easy Problem!
- poj2826 An Easy Problem?!
- HDOJ2055 An easy problem
- An Easy Problem
- hdu-An Easy Problem
- hdu2601 An easy problem
- An Easy Problem
- POJ3625 最小生成树
- 屠夫和狼
- 实战Nginx与PHP(FastCGI)的安装、配置与优化
- Suse集群测试总结
- 本地分支替换掉remote的分支
- 位运算 | 2453 | An Easy Problem
- 并行计算圆周率
- CSS 学习之我观
- 关于C++中类的static和const成员
- hdu 1068 Girls and Boys
- hrbeu Kth Largest (二重二分)
- 在Ubuntu上使用amule
- VS2010中配置CUDA5.0
- 存储系统的扩展:scale out VS scale up