卖萌的弱渣

I am stupid, I am hungry.

Pow(x,n)

Implement pow(x, n).

Solution

  • Divide and Merge
(Pow.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution(object):
    def power(self, x, n):
        if n == 0:
            return 1
        v = self.power(x,n/2)
        if n%2 == 0:
            return v*v
        else:
            return v*v*x

    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """

        # Divide and Merge
        # nlog(n)

        if n == 0:
            return 1
        if n == 1:
            return x

        if n < 0:
            return 1/self.power(x,-n)
        else:
            return self.power(x,n)