题目描述:
Implement pow(x, n).
Example 1:
Input: 2.00000, 10 Output: 1024.00000
Example 2:
Input: 2.10000, 3 Output: 9.26100
我的思路:
题目说明很简单,就是自己实现乘方运算。先试试循环但是估计不行哈。
试了两次水,大致问题是n的类型是int,所以有可能是负数和零,需要注意下。还有一个就是循环乘是不行的,会超时。用右移操作来减少循环次数,应该可以。还有一个事,是不是上溢要返回最大值,下溢返回0。基本就这么多问题吧。
我的代码:
class Solution:
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
rel = 1
m = abs(n)
while m:
if m & 1:
rel *= x
x *= x
m >>= 1
return rel if n > 0 else 1 / rel
Discuss:
Discuss中代码大同小异,基本都是这个意思,还有好多取巧的方法,就不学习了。
class Solution:
def myPow(self, x, n):
if not n:
return 1
if n < 0:
return 1 / self.myPow(x, -n)
if n % 2:
return x * self.myPow(x, n-1)
return self.myPow(x*x, n/2)
迭代也是一个好思路,可以学习一下。
学到:
这道题值得注意的一点是不需要判断溢出的条件,难道是题目不要求就不用求了?