您的位置:首页 > 其它

LeetCode 50: Pow(x, n)

2013-09-05 20:21 453 查看
Difficulty: 3

Frequency: 5

Problem:

Implement pow(x, n).

Solution:

1. Recursive solution from AnnieKim. Lots of subtleties.

class Solution {
public:
double pow(double x, int n) {
if (x < 0)
return (n % 2 == 0) ? pow(-x, n) : -pow(-x, n);
if (x == 1)
return x;
if (n < 0)
return 1.0 / pow(x, -n);
if (n == 0)
return 1.0;
if (n == 1)
return x;
double half = pow(x, n / 2);
if (n % 2 == 0)
return half * half;
else
return x * half * half;
}
};

2. Not that recursive one from MoreWindows.

class Solution {
public:
double powNotThatRecursive(double x, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (x==1||n==0)
return 1;

if (n==1)
return x;

if (x<0)
return (n&1)==0?pow(-x, n):-pow(-x, n);

if (n<0)
return 1.0/pow(x, -n);

double answer = 1;
while(n!=0)
{
if ((n&1)!=0)
answer *= x;

x *= x;
n >>= 1;
}
return answer;
}
};
Notes:

Thanks to AnnieKim and MoreWindows. This problem is very important. Should pay special attention to it.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: