Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
powx-n.cpp 843 Bytes
Copy Edit Raw Blame History
kamyu authored 2016-07-11 22:17 +08:00 . Update powx-n.cpp
// Time: O(logn) = O(1)
// Space: O(1)
// Iterative solution.
class Solution {
public:
double myPow(double x, int n) {
double result = 1;
long long abs_n = abs(static_cast<long long>(n));
while (abs_n > 0) {
if (abs_n & 1) {
result *= x;
}
abs_n >>= 1;
x *= x;
}
return n < 0 ? 1 / result : result;
}
};
// Time: O(logn) = O(1)
// Space: O(logn) = O(1)
// Recursive solution.
class Solution2 {
public:
double myPow(double x, int n) {
if (n < 0 && n != -n) {
return 1.0 / myPow(x, -n);
}
if (n == 0) {
return 1;
}
double v = myPow(x, n / 2);
if (n % 2 == 0) {
return v * v;
} else {
return v * v * x;
}
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

Search