Power of Two

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

method:code

1. recursive:orm

if x % 2 != 0, return false;blog

if x == 0, return false;it

if x == 1, return true;io

else, return isPowerOfTwo(x / 2);function

 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. trickform

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.class

1 class Solution {
2 public:
3     bool isPowerOfTwo(int n) {
4         return n > 0 && ((n & (n - 1)) == 0);
5     }
6 };
相關文章
相關標籤/搜索