Python Solution&Explanation [Power of Four]


  • 0
    P

    [My thoughts...]

    Given num is num>0 or num<0 and signed 32-bits.
    To return True, num should be a power of four: "num =4x4x4x....".


    (1) num will be 1, 4, 16, 64,....., which means "num>0".

    # 4 ** n
    4**0, 4**1, 4**2, 4**3.....
    

    (2) To get the value of n, " log(num)/log(4) ".

    import math
    n = math.log(num) / math.log(4)
    

    (3) Range of n is 0~15 : num is signed 32-bits, which means n is smaller than 32 / 2 (=16).

    n in range(0,16)
    

    (4) If n is 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
    or 0, 1.0, 2.0, 3.0, 4.0, 5.0, ................., 12.0, 13.0, 14.0, 15.0.
    ======> " n == int(n) " is True.


    (5) Return True or False whether num>0 and n in range(0,16) and n ==int(n) or not.



    [My solution is...]

    import math
    class Solution:
        def isPowerOfFour(self, num):
            self.num=num
            if num>0:
                n=math.log(num)/math.log(4)
                return n in range(0,16) and n == int(n)
            else:
                return False
    

Log in to reply
 

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