Implement the function double Power (double base, int exponent), find the exponent power of base. Don't use library functions, and don't need to consider large numbers.
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
Explanation:
-100.0 <x <100.0
n is a 32-bit signed integer with a value range of [−2 ^ 31, 2 ^ 31 − 1].
Source: LeetCode
Link: https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof
Copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.
Idea 1: Fast power
Convert the exponent to binary for analysis. Only 1 is required for calculation.
The first way of writing:
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
The second way of writing:
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