【LeetCode】50. Pow(x, n)

来源:互联网 发布:mac怎么登陆千牛 编辑:程序博客网 时间:2024/06/06 02:45
题目:

50. Pow(x, n)

DescriptionHintsSubmissionsSolutions
  • Total Accepted: 143792
  • Total Submissions: 539052
  • Difficulty: Medium
  • Contributor: LeetCode

Implement pow(xn).

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;
}

};

1 0
原创粉丝点击