-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0050_PowXN.cpp
More file actions
30 lines (26 loc) · 915 Bytes
/
0050_PowXN.cpp
File metadata and controls
30 lines (26 loc) · 915 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Problem 50: Pow(x, n)
// https://leetcode.com/problems/powx-n/
#include <vector>
using namespace std;
class Solution {
public:
double myPow(double x, int n) {
// 預設答案為 1, 宣告一個取絕對值的 n 為 positiveN
double ans = 1;
bool positive = n >= 0;
long long positiveN = (positive) ? n : -static_cast<long long>(n);
// 只要 positiveN 這個次方還沒有到 0, 就持續跑迴圈
while (positiveN > 0) {
// 如果這個次方是偶數, 就直接把底數平方, 次方除以2, 優化速度
if (positiveN % 2 == 0) {
x *= x;
positiveN /= 2;
}
// 正常乘一次, 次方減1
ans *= x;
positiveN--;
}
// 如果原先 n 是正數就回傳, 負數就回傳導數
return (positive) ? ans : 1 / ans;
}
};