[50. Pow(x, n)](https://leetcode.com/problems/powx-n/)
### 題目描述
Implement [pow(x, n)](https://cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., x^n^).
### 範例
**Example 1:**
```
Input: x = 2.00000, n = 10
Output: 1024.00000
```
**Example 2:**
```
Input: x = 2.10000, n = 3
Output: 9.26100
```
**Example 3:**
```
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
```
**Constraints**:
* -100.0 < `x` < 100.0
* -2^31^ <= `n` <= 2^31^-1
* `n` is an integer.
* Either `x` is not zero or `n > 0`.
* -10^4^ <= x^n^ <= 10^4^
### 解答
#### Javascript
```javascript=
function myPow(x, n) {
let result = 1;
while (n) {
if (n % 2) {
if (n > 0) {
result *= x;
} else {
result /= x;
}
}
x = x * x;
n = ~~(n / 2);
}
return result;
}
```
> [name=Marsgoat][time=Jul 24, 2023]
#### C++
``` cpp=
class Solution {
public:
double myPow(double base, int n) {
long long exponent = (long long) n;
if (exponent == 0) {
return 1;
}
if (exponent < 0) {
base = 1 / base;
exponent = -exponent;
}
double ans = 1;
while (exponent > 0) {
if (exponent % 2 == 1) {
ans *= base;
exponent -= 1;
}
base = base * base;
exponent /= 2;
}
return ans;
}
template<typename T>
void printVector(const vector<T>& vec) {
for (const T& element : vec) {
cout << element << ",";
}
cout << endl;
}
};
```
> [name=Jerry Wu][time=24 July, 2023]
### Reference
[回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)