1. 程式人生 > 其它 >leetcode50. Pow(x, n)

leetcode50. Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

Example 1:

Input: x = 2.00000, n = 10
Output: 1024.00000

Example 2:

Input: x = 2.10000, n = 3
Output: 9.26100

Example 3:

Input: x = 2.00000, n = -2

Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25


 

1. recursive

每次由n轉成n/2,這樣時間複雜度就是log(n)。n為0時,返回1

class
Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 1 if n < 0: return 1 / self.myPow(x, -n) # x = 1 / x # n = -n if n % 2 == 0: return self.myPow(x * x, n / 2) return x * self.myPow(x, n - 1)
# return x * self.myPow(x * x, n // 2)

 

2. iterative

N = 9 = 2^3 + 2^0 = 1001 in binary. Then:

x^9 = x^(2^3) * x^(2^0)

不斷右移二進位制n,每當碰到1時,res就乘上n的幾次方。右移的同時,x也每次乘自己,相當於走到第i位,x就是x^i。

n & 1 == 0, means divisible by 2

n >>= 1, 二進位制右移1位,等效於除2

  11 = 00001011 (Not divisible by 2)      28 = 00011100 (Divisible by 2)
&  1 = 00000001                         &  1 = 00000001
---------------                         ---------------
       00000001                                00000000
class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n < 0:
            n = -n
            x = 1 / x
        res = 1
        while n:
            if n & 1 == 1:
                res *= x
            n >>= 1
            x *= x
        return res