231. Power of Two

问题:

求给定数是否为2的幂。

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:
-2^31 <= n <= 2^31 - 1

  

解法:bit 运算。

  • n&(n-1)
  • 得到去掉末尾1位。

例如:0110->0100

若是2的幂,那么该数一定只有一个 1。

那么去掉这个 1 后,若该数==0,则为2的幂。

⚠️ 注意:这里要注意<=0的数,不可能为2的幂。

2^n>0,

因此,若<=0,直接返回false。

代码参考:

1 class Solution {
2 public:
3     bool isPowerOfTwo(int n) {
4         if(n<=0) return false;//2^x >0
5         return (n&(n-1))==0;
6     }
7 };
原文地址:https://www.cnblogs.com/habibah-chang/p/14569290.html