description
Implement pow(x, n). (n is an integer)
Description
Don't worry about accuracy, it is correct when the absolute value of the difference between the answer and the standard output is less than 1e-3
Sample
- 样例 1:
输入: x = 9.88023, n = 3
输出: 964.498
- 样例 2:
输入: x = 2.1, n = 3
输出: 9.261
- 样例 3:
输入: x = 1, n = 0
输出: 1
challenge
Time complexity O(logn)
Parsing
class Solution:
def myPow(self, x, n):
if x == 0:
return 0
if n < 0:
x = 1.0 / x
n = abs(n)
res = 1
while n != 0:
if n & 1:
res *= x
x *= x
n = n >> 1
return res