当前位置:   article > 正文

leetcode 50. Pow(x, n)【快速幂】

leetcode 50. Pow(x, n)【快速幂】

https://leetcode.com/problems/powx-n/description/

Implement pow(xn), which calculates x raised to the power n (xn).

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Note:

  • -100.0 < x < 100.0
  • n is a 32-bit signed integer, within the range [−231, 231 − 1]

这题可是不能再错了啊…………

都写多少遍了

结果还是忘记了n<0

  1. class Solution {
  2. public:
  3. double myPow(double x, int n) {
  4. if(x==0.0)
  5. return 0.0;
  6. if(n==0)
  7. return 1.0;
  8. bool flag=1;
  9. if(n<0)
  10. flag=0;
  11. double ans=1.0;
  12. while(n){
  13. if(n%2)
  14. ans=ans*x;
  15. n/=2;
  16. x=x*x;
  17. }
  18. if(flag)
  19. return ans;
  20. else
  21. return 1.0/ans;
  22. }
  23. };

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/421041
推荐阅读
相关标签
  

闽ICP备14008679号