[LeetCode] 077: Pow(x, n)

来源:互联网 发布:点餐系统数据库设计 编辑:程序博客网 时间:2024/05/17 23:22
[Problem]
Implement pow(x, n).

[Solution]
class Solution {
public:
double pow(double x, int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.

// special cases
if(n == 0)return 1;
if(fabs(x - 0) < 0.0000000001)return 0;

// x == 1
if(fabs(x - 1) < 0.0000000001)return 1;

// x == -1
if(fabs(x + 1) < 0.0000000001){
if(n % 2 == 0)
return 1;
else
return -1;
}

// x < 0
if(x < 0){
if(n % 2 == 0){
return pow(-x, n);
}
else{
return -pow(-x, n);
}
}

// n < 0
if(n < 0){
return 1/pow(x, -n);
}
if(n == 1){
return x;
}

// n is even
if(n % 2 == 0){
double half = pow(x, n/2);
return half * half;
}
else{
double half = pow(x, n/2);
return half * half * x;
}
}
};
说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击