[leetcode][math][bit] Power of Two
来源:互联网 发布:粒子群算法应用实例 编辑:程序博客网 时间:2024/05/22 11:14
题目:
Given an integer, write a function to determine if it is a power of two.
思路一:强解,如果一个数是2的n次方,那么它一定只有1和2两约数。注意:这里用移位运算">>"代替除法运算"/"使效率更高。
class Solution {public: bool isPowerOfTwo(int n) {if (n <= 0) return false;while (n != 1){if (n % 2 != 0) return false;n >>= 1;}return true;}};思路二:位运算,如果一个数是2的n次方,那么它一定只有一位是1其它位全是0。注意:"&"的优先级小于"=="所以括住n&(n-1)的括号是必需的。
class Solution {public: bool isPowerOfTwo(int n) { if(n <= 0) return false; return (n&(n-1)) == 0 ? true : false;}};
0 0
- [leetcode][math][bit] Power of Two
- Bit Manipulation - Power of Two
- [LeetCode] Power of Two
- 【LeetCode】Power of Two
- [Leetcode]Power of Two
- [leetCode] Power of Two
- leetcode --Power of Two
- leetcode: Power of Two
- LeetCode Power of Two
- [LeetCode] Power of Two
- LeetCode Power of Two
- [leetcode] Power of Two
- [Leetcode]Power of Two
- Leetcode: Power of Two
- [LeetCode]Power of Two
- leetcode | Power of Two
- 【leetcode】Power of Two
- [LeetCode]Power of Two
- C++中的字节对齐分析
- Java(Android)线程池
- otsu自适应阈值分割的算法描述和opencv实现,及其在肤色检测中的应用
- C++的深拷贝与浅拷贝
- pdf转word
- [leetcode][math][bit] Power of Two
- Visual Studio 2010 配置 openCV2.4.9
- 超简单的Ubuntu下安装Eclipse方法
- 《高效团队开发:工具与方法》
- spring boot实践
- Google文件系统
- Matlab常用工具箱
- (PHP 5.3 and above) Please set ‘request_order’ ini value to include C,G and P (recommended: ‘CGP’) i
- Eclipse启动时报错