4

LintCode 428. x的n次幂

 2 years ago
source link: https://www.purewhite.io/2018/07/11/lintcode-powx-n/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LintCode 428. x 的 n 次幂

发表于 2018-07-11 更新于 2021-12-02 分类于 算法 阅读次数: Disqus: 本文字数: 440 阅读时长 ≈ 1 分钟

实现 pow (x,n)

不用担心精度,当答案和标准输出差绝对值小于 1e-3 时都算正确

Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1

从数学上来说,(x)的4次方 等于 (x的平方)的平方。我们使用这个思想来做这道题就行了。

其实就和把十进制数转成二进制的思想是一样的。

需要注意的地方是,n 可能为负数。

class Solution:
"""
@param: x: the base number
@param: n: the power number
@return: the result
"""
def myPow(self, x, n):
if n == 0:
return 1
if x == 0:
return 0
t = x
if n < 0:
t = 1 / t
n = -n
ans = 1
while n != 0:
if n % 2 != 0:
ans *= t
t *= t
n = int(n / 2)
return ans

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK