一道简单的递归题

来源:互联网 发布:淘宝发送链接怎么发 编辑:程序博客网 时间:2024/06/05 20:38

题目描述如下:
Implement pow(x, n).
非常简单的一句话。
但這其中有一些坑。
就是INT_MIN的相反数,会溢出。
所以现将输入的参数强行转换为long防止这个问题。
代码如下:

 double myPow(double x, int n) {    if(x==0)         return 0;        long temp=n;        if(temp<0){                temp=-temp;                x=1/x;        }        if(n==0){            return 1;        }        if(temp/2>0){            double p=x*x;            if(n%2)                return myPow(p, temp/2)*x;            else                 return myPow(p, temp/2);        }        else            return x;    }
原创粉丝点击