Monday, April 11, 2016

LeetCode Q231: Power of Two

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


Solution 1:
class Solution {
public:
bool isPowerOfTwo(int n) {
double num = log2(n);
return n==0? false:num==round(num);
}
};
Solution 2:
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && !(n&(n-1));
}
};
view raw Q231-2.cpp hosted with ❤ by GitHub


Round 2 solution: Need to take care negtive number and zero:
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
return (n&(n-1))==0;
}
};
view raw Q231Rnd2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment