【LeetCode 231】Power of Two

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

思路:

  如果一个数是2的Power,那么该数的二进制串中只有一位为1,其余都为0。执行一次n & (n - 1)可消除最低位的一个1,若消除后为0,则说明该数是2的Power(n == 0 || n == -2147483648 时要特殊考虑)。

C++:

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

 

Python:

 1 class Solution:
 2     # @param {integer} n
 3     # @return {boolean}
 4     def isPowerOfTwo(self, n):
 5         if n == 0 or n == -2147483648:
 6             return False
 7         
 8         n = n & (n - 1)
 9         
10         if n == 0:
11             return True
12         else:
13             return False

 

posted @ 2015-07-06 12:35  tjuloading  阅读(306)  评论(0)    收藏  举报