leetcode[231]:Power of Two
2015-07-07 20:07
411 查看
Power of Two
Given an integer, write a function to determine if it is a power of two.
是2的整数次幂问题,很容易想到位操作。
看到了Discuss中某大神的做法,十分膜拜:
https://leetcode.com/discuss/44155/1-line-python-solution
转换成C语言如下:
前提: n>=0;
2的整数次幂换成二进制必然是1+x个0,n-1必然是x个1,n & n-1 必然全是0,实在是妙!!
Given an integer, write a function to determine if it is a power of two.
是2的整数次幂问题,很容易想到位操作。
看到了Discuss中某大神的做法,十分膜拜:
https://leetcode.com/discuss/44155/1-line-python-solution
转换成C语言如下:
bool isPowerOfTwo(int n) { return (n>0) && (n & (n-1))==0; }
前提: n>=0;
2的整数次幂换成二进制必然是1+x个0,n-1必然是x个1,n & n-1 必然全是0,实在是妙!!
相关文章推荐
- 一个有趣的SQL命题 用一条语句切换BIT型的真假值
- Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)
- Single Number II
- Bit与Byte的区别
- Bit manipulation
- HDU 1166 - 敌兵布阵 - Segment Tree
- poj 3109 扫描线+bit
- poj 2155 二维树状数组/区间更新单点查询
- 位操作 示例程序
- hdu 1556 Color the ball 树状数组
- hdu 2852 KiKi's K-Number 树状数组
- hdu1541 star 树状数组
- hdu 2838 Cow Sorting 树状数组
- 坑人的mysql中bit数据类型
- erlang 二进制与位语法(bit syntax)
- hdu3874Necklace(线段树或者BIT + 离线处理)
- POJ 2182 Lost Cows (递推)
- 字节、字、bit、byte的关系
- bit、sbin、sfr、sfr 16 区别分析
- Gray Code Leetcode Python