码迷,mamicode.com
首页 > 其他好文 > 详细

50. Pow(x, n)

时间:2020-03-24 00:43:21      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:注意   alt   int   div   精度   color   class   png   image   

题目描述:

实现 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
说明:

-100.0 < x < 100.0
n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。

思想:

 

 

技术图片

代码:

class Solution {
public:
    double fast_pow(double x,long long n){
        if(n<0){
            x = 1/x;
            n = abs(n);
        }
        if(n==0)
            return 1.0;
        double half = fast_pow(x*x,n/2);  //注意用double,float会损失精度
        if(n%2==0)
            return half;
        else 
            return half * x;
    }
    double myPow(double x, int n) {
        return fast_pow(x,n);
    }
};

 

50. Pow(x, n)

标签:注意   alt   int   div   精度   color   class   png   image   

原文地址:https://www.cnblogs.com/thefatcat/p/12556250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!