[LeetCode] Pow(x, n)

50. Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n (i.e. xn).

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
double myPow(double x, int n) {
long N = n < 0 ? -(long)n : n;
double res = 1;
while(N) {
res *= N & 1 ? x : 1;
N >>= 1;
x *= x;
}
return n < 0 ? 1 / res : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/05/PS/LeetCode/powx-n/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.