Implement pow(x, n).
明显的二分解决
由于n不可能总是偶数,
如果n是正奇数,那么n个x的乘积等于两部分的乘积再乘以x
如果n是负奇数,那么n个x的乘积等于两部分乘积再乘以1/x
class Solution { public: double pow(double x, int n) { if( n == 0) return 1.0; double half = pow(x,n/2); if(n%2 == 0) return half*half; else if(n > 0 ) return half*half*x; else return half*half/x; } };
也可以把负数n直接转换成正数再计算,递归方法:
class Solution { public: double pow(double x, int n) { if( n == 0) return 1.0; if( n == 1) return x; int exp =abs(n); double result = (exp%2 == 0) ? pow(x*x,exp/2):pow(x*x,exp/2)*x; return n < 0 ?1.0/result : result; } };
Leetcode Pow(x,n),布布扣,bubuko.com
原文:http://www.cnblogs.com/xiongqiangcs/p/3815256.html