231 Power of Two

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

The Idea: A number is a power of 2 if it has a single activated bit. E.g.

00000000000000001
00000000000000010
00000000000000100
...
10000000000000000

Complexity: O(1) time and space

class Solution:
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False

        cur_power = 1
        while cur_power <= n:
            if cur_power == n:
                return True
            cur_power <<= 1
        return False

Last updated