Power of Two

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

method:

1. recursive:

if x % 2 != 0, return false;

if x == 0, return false;

if x == 1, return true;

else, return isPowerOfTwo(x / 2);

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

 

2. trick

if x is power of 2, there is only one '1' in x(bit format). Using x & (x - 1) calculate the count of 1 in x.

1 class Solution {
2 public:
3     bool isPowerOfTwo(int n) {
4         return n > 0 && ((n & (n - 1)) == 0);
5     }
6 };

 

posted @ 2015-07-08 18:01  huj690  阅读(151)  评论(0编辑  收藏  举报