/*
50. Pow(x, n) My Submissions QuestionEditorial Solution
Total Accepted: 88936 Total Submissions: 319149 Difficulty: Medium
Implement pow(x, n).
Subscribe to see which companies asked this question
Show Tags
Show Similar Problems
*/
/*
解题思路:
使用二分思想求n次方,特殊情况 n=0 n为正数 n为负数
*/
class Solution {
public:
double myPow(double x, int n) {
//利用二分法思想(分治)
int i=n/2;
//如果n==0直接返回1
if(n==0)return 1;
//先计算一半
double t=myPow(x,i);
//如果是偶数
if(n%2==0) return t*t;
else {
//奇数且大于0
if(n>0)return t*t*x;
//奇数且小于0
else return t*t/x;
}
}
};