algorithm notes: leetcode#231 power of two

Problem


Solution


Initial thoughts

Python implementation

1
2
3
4
5
6
7
class (object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return (n > 0) and ((n & n-1) == 0)

Java implementation

1
2
3
4
5
class {
public boolean isPowerOfTwo(int n) {
return (n > 0) && ((n & n-1) == 0);
}
}

Time complexity

O(1).

Space complexity

O(1).


231. Power of Two
(中文版) 算法笔记: 力扣#231 2的幂