[LeetCode]Power of Two
Given an integer, write a function to determine if it is a power of two.
[思路]
1)考虑各种边界情况。
输入是整型值,说明不用考虑2的负指数情况。
2)假设一个数是二的倍数。说明他的二进制形式仅仅有一位是1。做好推断就可以。
循环推断1的位数解法最easy想到。
Leetcode上有种解法,就是让n&n-1,假设n仅仅含有一个1那么结果就是零。
简单解法:
class Solution {
public:
    bool isPowerOfTwo(int n) {
       if(n<=0) return false;
       int count = 0;
       while(n!=0){
           if(n%2!=0){
               count++;
           }
           n = n>>1;
           if(count>1)
            return false;
       }
        return true;
    }
};奇妙解法:
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n<=0)
            return false;
        n &= n-1;
        return n==0 ;
    }
}; 
                    
                
 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号