Python. easy to understand with comments

  • 0

    the idea is really simple :) the binary of power of fours have only one 1 and the 1 is in the odd position of the binary. ex: bin(4^0)=1 (has only one 1 and the 1 is in an odd position), bin(4^1)=100 (has only one 1 and the 1 is in an odd position). Same can be said about all the power of fours.

    In this code, Ive a counter to count the number of 1's in binary, and have a flag to see where the 1 occurs. The flag is set if the 1 is in a odd position.

    For the num to be a power of four, the counter must equal 1 and flag must equal True

    class Solution(object):
        def isPowerOfFour(self, num):
            :type num: int
            :rtype: bool
            if num<0:
                return False
            while num!=0:
                if num&1==1:
                    if i%2==1:
            if count==1 and oddFlag==True:
                return True
            return False

Log in to reply

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