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
Example 4:
Input: n = 4 Output: true
Example 5:
Input: n = 5 Output: false
Constraints:
-231 <= n <= 231 - 1
Solution: 1 bit set
Any power of two has only 1 bit set in the binary format. e.g. 1=0b01, 2=0b10, 4=0b100, 8=0b1000
- use popcount.
C++
1 2 3 4 5 6 7 |
// Author: Huahua class Solution { public: bool isPowerOfTwo(int n) { return n > 0 ? __builtin_popcount(n) == 1 : false; } }; |
2. Use (n) & (n – 1) to remove the last set bit, so it should be zero.
C++
1 2 3 4 5 6 7 |
// Author: Huahua class Solution { public: bool isPowerOfTwo(int n) { return n > 0 ? !(n & (n - 1)) : false; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment