###### tags: `Leetcode` `easy` `math` `bit` `python` `c++` # 231. Power of Two ## [題目連結:] https://leetcode.com/problems/power-of-two/description/ ## 題目: Given an integer ```n```, return ```true``` if it is a power of two. Otherwise, return ```false```. An integer ```n``` is a power of two, if there exists an integer ```x``` such that ```n == 2x```. **Example 1:** ``` Input: n = 1 Output: true Explanation: 20 = 1 ``` **Example 2:** ``` Input: n = 16 Output: true Explanation: 24 = 16 ``` **Example 3:** ``` Input: n = 3 Output: false ``` **Follow up:** Could you solve it without loops/recursion? ## 解題想法: * 此題為判斷給的數是否為2的冪次方 * 簡易解: * 直接while迴圈累除2判斷即可 * 解Follow up: * 使用**Bit**判斷 * 若n為2的冪次方: * 其二進制為:10...0 * 則(n-1)為二進制為:01111....1 * **兩者做and為0** ## Python: ``` python= class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ #法1 #若n為2的冪次方,二進制為 10...0,則(n-1)為01111....1 兩者做and為0 if n<=0: return False else: # 0為fasle 所以要加個not才負負的正 return not (n&(n-1)) ''' #法2 while n: if n%2 ==0: n = n//2 elif n==1: return True else: return False ''' if __name__ == '__main__': n = 16 result = Solution() ans = result.isPowerOfTwo(n) print(ans) ``` ## C++: ``` cpp= class Solution { public: bool isPowerOfTwo(int n) { if (n<=0) return false; else return !(n&(n-1)); } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up