题目:
50. Pow(x, n)
- Total Accepted: 143792
- Total Submissions: 539052
- Difficulty: Medium
- Contributor: LeetCode
Implement pow(x, n).
Subscribe to see which companies asked this question.
解题思路:pow(x,n)即n个x相乘,用二分的思想,当n为偶数时,可以表示为pow(x,n/2)*pow(x,n/2),当n为基数时,可以表示为pow(x,n/2)*pow(x,n/2)*x.
解答:
class Solution {
public:
double myPow(double x, int n) {
if(n < 0){
return 1.0/myPow1(x,-n);
}
else{
return myPow1(x,n);
}
}
double myPow1(double x,int n){
if(n == 0){
return 1.0;
}
double y = myPow1(x,n/2);
if(n & 1){
return y*y*x;
}
else{
return y*y;
}
}
};