Python solution with explanation

  • 0
    1. since the integer is a power of two, so it is an positive number.
    2. if a number is a power of two, it can be divided by two repeatedly until the result is one, and this is an binary right shift operation, so there must be only one '1' in the binary representation of the number.
    class Solution(object):
        def isPowerOfTwo(self, n):
            :type n: int
            :rtype: bool
            return n > 0 and bin(n).count('1') == 1

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.