标签:blog http io 2014 amp log .net on
原题:
Implement pow(x, n).
思路:递归计算pow。
class Solution { public: double pow(double x, int n) { long long int mid = n/2; int d = n%2; if(n==0) return 1; if(n==1) return x; if(d==1) return pow(x, (n/2)+1) * pow(x, n/2); else return pow(x, n/2) * pow(x, n/2); } };
边界值处超时。
int -2147483648 ~ +2147483647 (4 Bytes)
class Solution { public: double pow(double x, int n) { long long num = n; if(num==0) return 1.0; if(num==1) return x; if(num<0) return 1.0/pow(x, -num); double half = pow(x,num>>1); if(num%2==0) return half*half; else return half*half*x; } };此时n若为负值,取负后即溢出。RE
class Solution { public: double pow(double x, int n) { if(n==0) return 1.0; if(n==1) return x; if(n<0 && n!=INT_MIN) return 1.0/pow(x, -n); if(n==INT_MIN) return 1.0/(pow(x, INT_MAX)*x); double half = pow(x,n>>1); if(n%2==0) return half*half; else return half*half*x; } };要考虑到最小的INT_MIN,即-2147483648取负会溢出,所以需要特殊处理。
AC
【Leetcode长征系列】Pow(x, n),布布扣,bubuko.com
标签:blog http io 2014 amp log .net on
原文地址:http://blog.csdn.net/u010239096/article/details/38557697