Pow(x, n)

实现pow(x , n)函数。

这里我们看下自带的math.h里是怎么实现的。

//自带实现

template<class _Ty> inline
        _Ty _Pow_int(_Ty _X, int _Y)
        {unsigned int _N;
        if (_Y >= 0)
                _N = (unsigned int)_Y;
        else
                _N = (unsigned int)(-_Y);
        for (_Ty _Z = _Ty(1); ; _X *= _X)
                {if ((_N & 1) != 0)
                        _Z *= _X;
                if ((_N >>= 1) == 0)
                        return (_Y < 0 ? _Ty(1) / _Z : _Z); }}

加入题目要求的double类型实例化为:

  double pow(double x, int n) {
     unsigned int N;
     if(n >= 0) N = (unsigned int)n;
     else N = (unsigned int)(-n);
     for(double z = 1; ; x *= x ){
         if((N & 1) != 0)
         z *= x;
         if((N >>= 1) == 0)
         return (n < 0 ? 1/z : z);
     }
    }
这个问题我们也可以想到递归:

看一下discuss里面一位coder的问题:

 double pow(double x, int n) {
        if(n==0) return 1;
        if(n==1) return x;
        if(x==0) return x;
        if(n<0) return pow(1/x, -n);
        if(n%2) return x*pow(x*x, n/2);
        else return pow(x*x, n/2);
    }
Last executed input: 1.00000, -2147483648

However, my code below works! I just change one line! But, I think both are same!

class Solution {
public:
    double pow(double x, int n) {
        if(n==0) return 1;
        if(n==1) return x;
        if(x==0) return x;
        if(n<0){
            x = 1/x;
            n = -n;
        }

        if(n%2) return x*pow(x*x, n/2);
        else return pow(x*x, n/2);
    }
}

问题是
if(n<0) return pow(1/x, -n);
这条语句,我们看下到底是怎么回事,int 范围是 - 2147483648 ~ 2147483647,所以 -n  还是 -2147483648,那么递归的时候就出现问题了,是的,死循环,在我们的本机环境中会报 “stack overflow” 异常。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值