【leetcode】Pow(x,n)
1,483 views
0
Question:
Implement pow(
x
,
n
).
Answer 1:
O(n)
class Solution {
public:
double pow(double x, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n == 0) return 1;
if(x == 0) return 0;
bool flag = false; // is negative
if(n < 0) {
flag = true;
n = -n;
}
/*
double ret = 1;
for(int i = 0; i < n; ++i){ // error when n is max integer, such as n = 2147483647 overflow
ret *= x;
}
*/
double tmp = x;
double ret = 1;
while(n > 0) {
if(n & 1 == 1){ // or (n & 1) or (n % 2) or (n % 2 == 1)
ret *= tmp;
}
tmp *= tmp;
n >>= 1;
}
return flag ? 1.0/ret : ret;
}
};
注意点:
题目非常简单,担忧许多细节需要考虑
1) x = 0 或 n = 0
2) n 为正或负数
3) n为正整数边界值(error 错误)
Answer 2:
O(log(n))
class Solution {
public:
double pow2(double x, int n){
if(n == 0){
return 1;
}
double mul = pow2(x, n/2);
if(n & 1) {
return x * mul * mul;
} else {
return mul * mul;
}
}
double pow(double x, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n < 0){
return 1.0 / pow2(x, -n);
} else {
return pow2(x, n);
}
}
};
注意点:
1) 递归二分法
2) n为正/负数
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2013-04-12 23:17:26
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!