Simple iterative Python

  • 0

    the value of power of 2 must not be negative.
    So eliminate the negative situation.
    Then we get started to divide n by 2 iteratively.
    At very end, if n can be totally divided by 2, 1 is finally left.

    class Solution(object):
        def isPowerOfTwo(self, n):
            :type n: int
            :rtype: bool
            if n <= 0:
                return False
            while n % 2 == 0:
                n = n / 2
            return n == 1

Log in to reply

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