[LeetCode]50 Pow(x, n)

题目描述

实现 pow(x, n) ,即计算 x 的 n 次幂函数。

示例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

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
total = 1
flag = True
if n < 0:
n = -n
flag = False
while n > 0:
temp = n % 2
if temp:
total *= x
x *= x
n = n >> 1
if flag :return total
else: return 1 / total
return res if n >= 0 else 1 / res