Python Bitwise Shift Iteration


  • 2
    B

    The idea is to count the amount of 1's that appear in the binary representation of n. If c is anything other than 1, then n is not a power of 2. All powers of 2 in a binary representation will have exactly one 1 in it.

    2^0 = 0001
    2^1 = 0010
    2^2 = 0100
    2^3 = 1000
    ...

    class Solution(object):
        def isPowerOfTwo(self, n):
            c = 0
            while n > 0:
                if n & 1:
                    c += 1
                n >>= 1
            return True if c == 1 else False
    

  • 0
    Z

    @betts So brilliant!!!
    I refine that a little bit, add a condition to save it do less work :D

    class Solution(object):
        def isPowerOfTwo(self, n):
            """
            :type n: int
            :rtype: bool
            """
            c = 0
            while n > 0:
                if n&1:
                    c += 1
                    if c>1:
                        return False
                n >>= 1
            return True if c else False
    

Log in to reply
 

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