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.
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.
相关文章推荐
- [LeetCode 50] Pow(x, n)
- LeetCode 50: Pow(x, n)
- LeetCode - 50/69/367/633 - Pow(x, n)、Sqrt(x)
- [LeetCode-Algorithms-50] "Pow(x, n)" (2017.10.25-WEEK8)
- leetcode50 Pow(x, n)
- leetcode-50-Pow(x, n)
- LeetCode-50 Pow(x, n)
- (java)leetcode-50:Pow(x, n)
- [LeetCode-50] Pow(x, n)(数值的整数次方)
- leetcode 50 : Pow(x, n)
- 50. Pow(x, n) LeetCode
- Pow(x, n) - LeetCode 50
- 【LeetCode 50】Pow(x, n)
- leetcode 50 Pow(x, n)
- Leetcode 50 Pow(x, n) 两种方式求解
- [Leetcode] 50 - Pow(x, n)
- Leetcode(50):Pow(x, n)
- 【LeetCode】50、pow(x,n)
- leetcode-50-pow
- LeetCode50 pow(x, n)