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 @   huj690  阅读(151)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示