Pow(x, n) LeetCode solution in C++

1
class Solution {
2
public:
3
double myPow(double x, int n) {
4
if (n == 0) return 1; // anything to the power 0 is 1
5

6
if (x == 1 || n == 1) return x; // 1 to the power anything = 1 or x to the power 1 = x
7

8
double ans = 1;
9

10
long long int a = abs(n); // since int range is from -2147483648 to 2147483647, so it
11
// can't store absolute value of -2147483648
12

13
if (n < 0) { // as 2^(-2) = 1/2^2
14
if (a % 2 == 0)
15
ans = 1 / myPow(x * x, a / 2);
16
else
17
ans = 1 / (x * myPow(x, a - 1));
18
} else {
19
if (a % 2 == 0)
20
ans = myPow(x * x, a / 2);
21
else
22
ans = x * myPow(x, a - 1);
23
}
24

25
return ans;
26
}
27
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0