首页 > 其他 > 详细

leetcode50 Pow(x, n)

时间:2020-02-26 00:20:51      阅读:73      评论:0      收藏:0      [点我收藏+]
 1 """
 2 Implement pow(x, n), which calculates x raised to the power n (xn).
 3 Example 1:
 4 Input: 2.00000, 10
 5 Output: 1024.00000
 6 Example 2:
 7 Input: 2.10000, 3
 8 Output: 9.26100
 9 Example 3:
10 Input: 2.00000, -2
11 Output: 0.25000
12 Explanation: 2-2 = 1/22 = 1/4 = 0.25
13 """
14 class Solution:
15     def myPow(self, x, n):
16         if n < 0:
17             x = 1 / x  # 巧妙的转换了n<0的情况
18             n = -n
19         res = 1.0
20         while n:
21             if n % 2 != 0:  # n & 1  与运算高级写法,快了一点
22                 res *= x
23         x *= x
24         n = n // 2  # n >>= 1
25         return res

 

leetcode50 Pow(x, n)

原文:https://www.cnblogs.com/yawenw/p/12364656.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!