力扣面试150 Pow(x, n) 快速幂 负指数
Problem: 50. Pow(x, n)
解题方法
👨🏫 参考题解
复杂度
时间复杂度: O ( l o g 2 n ) O(log_{2}n) O(log2n)
空间复杂度: O ( 1 ) O(1) O(1)
Code
class Solution {public double myPow(double x, int n){if (x == 0.0f)return 0.0d;long b = n;double res = 1.0;if (b < 0)// 指数是 负数{x = 1 / x;b = Math.abs(b);}while (b > 0)// 经典快速幂{if ((b & 1) == 1)res *= x;x *= x;b >>= 1;}return res;}
}