Power of Two

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

Analyse: ***Notice that if a number is a power of 2, then the highest binary digit is 1 and the remaining digits are all 0s. So n & (n-1) = 0. If a number is not a power of 2, then n & (n - 1) != 0.

Runtime: 4ms.

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n <= 0 ) return false;
        
        return (n & (n - 1)) == 0;
    }
};

 

Other solution:

1. Runtime: 8ms.

 1 class Solution {
 2 public:
 3     bool isPowerOfTwo(int n) {
 4         if(n <= 0 ) return false;
 5         
 6         int remain = 1;
 7         while(n != 1){
 8             remain = n % 2;
 9             if(remain == 1) return false;
10             n /= 2;
11         }
12         return true;
13     }
14 };

2. Rutime: 8ms

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

 

posted @ 2015-08-29 06:10  amazingzoe  阅读(156)  评论(0编辑  收藏  举报