Implement pow(x, n).
实现pow(x, n)
最直接的思路是用一个循环,乘n次的x。
class Solution { public: double pow(double x, int n) { if(x==0)return 0; //两种特殊情况 if(n==0)return 1; double result=1; bool isNegative= n<0?true:false; long long nTotal= isNegative? -1*n : n; long long nUsed=1; long long nUsedTotal=0; double multiply=x; while(nUsedTotal<nTotal){ nUsed=1; multiply=x; while(nUsed*2<nTotal-nUsedTotal){ nUsed*=2; multiply = multiply*multiply; } nUsedTotal+=nUsed; result*=multiply; } if(isNegative) return 1/result; return result; } };
LeetCode: Pow(x, n) [049],布布扣,bubuko.com
原文:http://blog.csdn.net/harryhuang1990/article/details/26668929