๐ ๐ 50. Pow(x, n)
2022ๅนด10ๆ10ๆฅ
- algorithm
๐ ๐ 50. Pow(x, n)
้พๅบฆ: ๐ ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
public double myPow(double x, int n) {
// ๆ่ทฏ๏ผ
// ๅฟซ้ๅน
// x^n = x^(n / 2) * x^(n / 2) ๏ผๅฆๆ n % 2 == 1 ่ฟ้่ฆ * cur
if(x == 0) {
return 0;
}
if(n == 0) {
return 1;
}
int flag = 1;
long nn = (long) n; // ๆ้ค่ดๆฐ่ๅด็ๅฝฑๅ
if(n < 0) {
nn = -nn;
flag = -1;
}
double res = 1.0;
double cur = (double)x;
// System.out.println(nn);
while(nn > 0) {
long left = nn % 2;
nn /= 2;
if(left == 1) {
res *= cur; // ๅๅบๆฅ๏ผ่ฟ้่ฆๅคไนไธๆฌก
}
cur *= cur;
}
// System.out.println(res);
if(flag > 0) {
return res;
} else {
return (double)1 / res;
}
}
}