How is this so easy?


  • -5
    A
    class Solution(object):
        def myPow(self, x, n):
            """
            :type x: float
            :type n: int
            :rtype: float
            """
        
            y = x ** n
            return y

  • 0
    A

    was the solution supposed to be this easy, or did I accidentally "cheat".


  • 0
    A
    class Solution(object):
        def myPow(self, x, n):
            """
            :type x: float
            :type n: int
            :rtype: float
            """
            return x ** n

  • 1

    I think you did cheat. I believe the problem is asking you to implement pow, not to use a readily provided implementation. That would be like calling sort if you're asked to implement a sorting algorithm.


  • 2
    A

    Guess what, my dad taught me this new way of doing it:

    class Solution(object):
        def mypow2(self, x, n):
            if n == 1:
                return x
            elif n == 0:
                return 1
            elif n & 1 == 0:
                t = self.mypow2(x, (n/2))
                return t * t
            else:
                t = self.mypow2(x, (n-1)/2)
                return t * t * x
        def myPow(self, x, n):
            """
            :type x: float
            :type n: int
            :rtype: float
            """
            if n < 0:
                return (1/self.mypow2(x, 0 - n))
            else:
                return self.mypow2(x, n)

Log in to reply
 

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