#Leetcode# 231. Power of Two
阿新 • • 發佈:2018-11-15
ftw urn n) integer cti put term cpp brush
https://leetcode.com/problems/power-of-two/
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1 Output: true Explanation: 20 = 1
Example 2:
Input: 16 Output: true Explanation: 24 = 16
Example 3:
Input: 218 Output: false
題解:$2$ 的 $n$ 次冪二進制是只有一個 $1$ 後面 $n$ 個 $0$ ,如果減去 $1$ 之後就 $1$ 變成 $0$, $0$ 變成 $1$ 所以判斷方法為 $(n & (n - 1) == 0)$
代碼:
class Solution { public: bool isPowerOfTwo(int n) { if(n <= 0) return false; if((n & (n - 1)) == 0) return true; return false; } };
#Leetcode# 231. Power of Two