LeetCode 231. Power of Two --Easy
阿新 • • 發佈:2019-02-10
Given an integer, write a function to determine if it is a power of two.
方法一、
迭代判斷n/2是不是2的乘冪
<pre name="code" class="cpp">class Solution { public: bool isPowerOfTwo(int n) { if(n==1 || n==2) return true; if(n<1) return false; if(n%2 !=0) return false; return isPowerOfTwo(n/2); } };
方法二、
如果n是2的乘冪,則其二進位制表示中只有一個1,我們可以統計其中的1的個數。
};class Solution { public: <pre name="code" class="cpp"> bool isPowerOfTwo(int n) { <span style="white-space:pre"> </span>int count = 0; <span style="white-space:pre"> </span>while (n > 0) { <span style="white-space:pre"> </span>count+=(n&0x01); <span style="white-space:pre"> </span>n>>=1; <span style="white-space:pre"> </span>} return count==1; }
方法三、
如果n是2的乘冪,則其二進位制表示中只有最高位是1,其他都是0,我們只需將n 和(n-1)求與,若結果為0,則true。
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n>0) && (!(n&(n-1)));
}
};
github程式碼: