一、Problem
Implement pow(x, n), which calculates x raised to the power n (xn).
Input: 2.00000, 10
Output: 1024.00000
二、Solution
方法一:快速冪
注意的幾點:
- 當 n 爲負數時,需要將底數 x 顛倒一下,但冪數依舊要整數才能進行快速冪
- 方法給定的參數 n 是整形,其最大範圍爲 也就是說,如果對 取反會產生溢出,一般的做法是將 n 轉爲 long 在取反。
class Solution {
double quick(double b, long p) {
double res = 1.0;
while (p > 0) {
if ((p & 1) == 1)
res *= b;
p = p >>> 1;
b *= b;
}
return res;
}
public double myPow(double x, int n) {
long p = n;
if (p < 0) {
x = 1 / x;
p = -p;
}
return quick(x, p);
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,
還有其他分治啥的,代辦把…