Leetcode 231. Power of Two

Given an integer, write a function to determine if it is a power of two.

题目大意:判断一个数是否是2的指数次。

思路一:如果一个数是2的指数次,那么它对应的二进制数中只有一个1;利用位运算即可解决。‘

 1 class Solution {
 2 public:
 3     bool isPowerOfTwo(int n) {
 4         int k = 0;
 5         while(n > 0){
 6             if(n & 1)
 7                 k++;
 8             n >>= 1;
 9         }
10         if(k == 1)
11             return true;
12         return false;
13     }
14 };

 思路二:如果一个整数是2的幂,那么有 (n & (n-1)) == 0;

1 bool isPowerOfTwo(int n){
2         if(n <= 0)
3             return false;
4         return ((n & (n - 1)) == 0);
5     }
原文地址:https://www.cnblogs.com/qinduanyinghua/p/5727673.html