1. 程式人生 > >[LeetCode] 50. Pow(x, n)

[LeetCode] 50. Pow(x, n)

題目

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

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

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

Note:

-100.0 < x < 100.0 n is a 32-bit signed integer, within the range [−231

, 231 − 1]

思路

題目大意

計算pow(x,n)

解題思路

1.遞迴相乘計算

xn 可以看做 x(n/2)2 ,(x(n/2) )2。具體來說,計算 x6 = x3 x3。由這樣的方式可產生 最後的 x6。 但需要注意的是,x3 時,需要分解為x * x1 * x1。故對於 n為奇數時,需要n-1,同時將res*=x。

2.指數分解法

將 n 分解為 2的指數形式,然後利用指數性質進行計算。

eg:計算 37 7 = 2^2 + 2^1 + 2^0

  1. 設 原結果tsum = 37 =32^2 + 2^1 + 2^0 。res =1
  2. tsum&1 = 1,res =3。計算 res
    32^2 + 2^1
  3. 令 tsum = 32^2 + 2^1 ,則 tsum = 322^1 + 2^0,令 3 = 3 ,為9,則 tsum = 92^1 + 2^0;(2^1 + 2^0) &1 ==1, res =3 * 3,計算 res *92^1 同理當 指數為0時候 結束。

code

1.遞迴相乘計算

class Solution:

    def eleMypow(x,n):
        tmp = 1
        if n & 1== 1:
            tmp *= x
        if n >>1
!=0: eres = Solution.eleMypow(x, n >> 1) tmp *= eres*eres return tmp def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n<0: return 1/Solution.eleMypow(x,-n) else: return Solution.eleMypow(x,n)
class Solution:
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """

        absn = abs(n)
        res = 1
        while absn > 0 :
            if absn&1 == 1:
                res *= x
            x*=x
            absn = absn>>1
        return res if n >=0 else 1/res