Leetcode 50. Pow(x, n)

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Pow(http://noahsnail.com/images/leetcode/Pow(x,_n).jpeg)

2. Solution

  • Iterative
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
double myPow(double x, int n) {
double result = 1.0;
long m = labs(n);
x = n>0?x:1/x;
while(m) {
if(m & 1) {
result *= x;
}
x *= x;
m >>= 1;
}
return result;
}
};
  • Recursive
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
double myPow(double x, int n) {
x = n>0?x:1/x;
long m = labs(n);
return power(x, m);
}

double power(double x, long n) {
if(n == 0) {
return 1;
}
if(n % 2) {
return x * power(x * x, n / 2);
}
else {
return power(x * x, n / 2);
}
}
};

Reference

  1. https://leetcode.com/problems/powx-n/description/
如果有收获,可以请我喝杯咖啡!