関数double Power(double base、int exponent)を実装し、baseの指数指数を求めます。ライブラリ関数を使用しないでください。また、多数を考慮する必要はありません。
例1:
入力:2.00000、10
出力:1024.00000
例2:
入力:2.10000、3
出力:9.26100
例3:
入力:2.00000、-2
出力:0.25000
説明:2-2 = 1/22 = 1/4 = 0.25
説明:
-100.0 <x <100.0
nは、値の範囲が[-2 ^ 31、2 ^ 31-1]の32ビット符号付き整数です。
ソース:LeetCode
リンク:https ://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof
著作権は控除ネットワークに属しています 商用転載の正式な許可書に連絡し、非商用転載の出典を明記してください。
アイデア1:高速パワー
指数を分析のためにバイナリに変換します。計算に必要なのは1つだけです。
最初の書き方:
class Solution:
def myPow(self, x: float, n: int) -> float:
f = 1
if n < 0:
n = -n
f = 0
base = x
ans = 1
while n:
if n & 1:
ans *= base
base *= base
n //= 2
if f == 0:
ans = 1/ans
return ans
2番目の記述方法:
class Solution:
def myPow(self, x: float, n: int) -> float:
if x == 0:
return 0
if n < 0:
x, n = 1/x, -n
ans = 1
while n:
if n & 1:
ans *= x
x *= x
n >>= 1
return ans