</pre>Pow(x, n)</h1><h1><span style="color:#3333ff;">1、分析</span></h1><div><span style="font-size:18px;">函数原型double pow(double x, int n),实现求x的n次方。</span></div><div><span style="font-size:18px;"></span></div><div><span style="font-size:18px;">有一点需要注意:int n类型范围 -2147483648~2147483647当n=-2147483648,则-n=2147483648超出2147483647,结果仍然是-2147483648,所以应该单独处理。</span></div><div><span style="font-size:18px;">也可以用机器码来解释这一个知识点:-2147483648的机器吗为1000...0000(32位),取负,即机器码各位取反后加1,得到的还是100....000。这也是代码中if(n<0 && n!=INT_MIN) return 1.0/pow(x,-n) 为什么这样写的原因,如果写成if(n<0) return 1.0/pow(x,-n) 则会造成死循环</span></div><h1><span style="color:#3333ff;">2、正解代码</span></h1><div><span style="font-size:18px;">分治法</span></div><div><pre name="code" class="cpp"><span style="font-size:18px;">class Solution { public: double pow(double x, int n) { if(n<0 && n!=INT_MIN) return 1.0/pow(x,-n); else if(n==INT_MIN) {double val=pow(x,-(n/2)); return 1.0/val*val;} else if(n==0) return 1.0; else if(n%2==1) {double val=pow(x,(n-1)/2);return x*val*val; } else {double val=pow(x,n/2);return val*val;} } };</span>
double pow(double x, int n) { if(n<0 && n!=INT_MIN) return 1.0/pow(x,-n); else if(n==INT_MIN) return 1.0/(pow(x,-(n/2))*pow(x,-(n/2))); else if(n==0) return 1.0; else if(n%2==1) return x*pow(x,(n-1)/2)*pow(x,(n-1)/2); else return pow(x,n/2)*pow(x,n/2);
<span style="font-size:18px;">class Solution { public: int sqrt(int x) { //x不会小于0 if(x==0) return 0; long long int first=1,last=x; while(first<last){ long long int mid=(first+last)/2; if(mid*mid<x) first=mid+1; //long long类型与int类型比较,int被暂时当作long long? else if(mid*mid>x) last=mid-1; else return mid; } if(first*first>x) return first-1; else return first; } };</span>
【leetcode 分治法】Pow(x, n)与Sqrt(x)函数的实现
原文地址:http://blog.csdn.net/u012162613/article/details/41361655