[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
原创粉丝点击