Power of Two
LeetCode: Power of Two
Problem:
Given an integer, write a function to determine if it is a power of two.
- Analysis:
(n > 0) && (n & (n - 1)) == 0
- Code - Java:
class Solution {
public boolean isPowerOfTwo(int n) {
return (n > 0) && (n & (n - 1)) == 0;
}
}
- Code - C++:
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0) && (n & (n - 1)) == 0;
}
};
- Code - Python:
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return (n > 0) and (n & (n - 1)) == 0
- Code - C:
bool isPowerOfTwo(int n) {
return (n > 0) && (n & (n - 1)) == 0;
}