Given an integer, write a function to determine if it is a power of two.
Solution:
class Solution {
public:
bool isPowerOfTwo(int n) {
/*
if (n == 0)
return false;
else if (n == 1)
return true;
else if (n % 2 == 0)
return isPowerOfTwo(n/2);
else
return false;
*/
// Iterative.
/*
while (n > 1) {
if (n % 2 != 0) {
return false;
}
n /= 2;
}
return n == 1;
*/
// Bitwise.
if (n > 0 && !(n & (n - 1))) {
return true;
}
return false;
}
};
Solution:
class Solution {
public:
bool isPowerOfTwo(int n) {
/*
if (n == 0)
return false;
else if (n == 1)
return true;
else if (n % 2 == 0)
return isPowerOfTwo(n/2);
else
return false;
*/
// Iterative.
/*
while (n > 1) {
if (n % 2 != 0) {
return false;
}
n /= 2;
}
return n == 1;
*/
// Bitwise.
if (n > 0 && !(n & (n - 1))) {
return true;
}
return false;
}
};
No comments:
Post a Comment