Problem
Given an integer, write a function to determine if it is a power of two.
Example
Input: 2
Output: true
Algorithm
整理一下題意:給定一個整數,判斷其是否是2的冪。
簡單判斷即可。注意特殊情況,如負數,0,1。
代碼如下。
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0) return false;
bool isp=true;
while(n){
if(n%2==1&&n!=1){
isp=false;
break;
}
n/=2;
}
return isp;
}
};