Python one line solution with explanations


  • 27
    C
    def isPowerOfFour(self, num):
            return num != 0 and num &(num-1) == 0 and num & 1431655765== num
    

    Consider the valid numbers within 32 bit, and turn them into binary form, they are:

    1
    100
    10000
    1000000
    100000000
    10000000000
    1000000000000
    100000000000000
    10000000000000000
    1000000000000000000
    100000000000000000000
    10000000000000000000000
    1000000000000000000000000
    100000000000000000000000000
    10000000000000000000000000000
    1000000000000000000000000000000
    

    Any other number not it the list should be considered as invalid.
    So if you XOR them altogether, you will get a mask value, which is:

    1010101010101010101010101010101 (1431655765)
    

    Any number which is power of 4, it should be power of 2, I use num &(num-1) == 0 to make sure of that.
    Obviously 0 is not power of 4, I have to check it.
    and finally I need to check that if the number 'AND' the mask value is itself, to make sure it's in the list above.

    here comes the final code:

    return num != 0 and num &(num-1) == 0 and num & 1431655765== num


  • 1
    J

    Nice explanation. Thanks :)


  • 0
    Q

    @chris.zhang.336 said in Python one line solution with explanations:

    num &(num-1) == 0

    num &(num-1) == 0 matches the power of 2 as well as power of 4, and it filters the some number like '101' which matches the num & 1431655765== num


Log in to reply
 

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