50. Pow(x, n)
Asked at 21Meta84Bloomberg61Google54Microsoft53Amazon53Wix87eBay77LinkedIn70tcs59Qualcomm58ServiceNow55EPAM Systems51Citadel47Adobe44Walmart Labs43Zoho42Nvidia39Cisco37Goldman Sachs36Infosys30Oracle27
Problem
Compute xⁿ for a float x and an integer n, which may be negative.
Example: x = 2.0, n = 10 → 1024.0; x = 2.0, n = -2 → 0.25
Constraints: n is a 32-bit integer; aim for O(log n) multiplications.
Binary exponentiation: x^n = (x²)^(n/2) (· x if n is odd). Negative n → 1 / x^(−n) (use a long for −Integer.MIN_VALUE).
x^13, 13 = 1101b
bit 1: res *= x x -> x^2
bit 0: x^2 -> x^4
bit 1: res *= x^4 x^4 -> x^8
bit 1: res *= x^8 => x^(1+4+8) = x^13
Complexity: O(log n).
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
x, n = 1 / x, -n
res = 1.0
while n:
if n & 1:
res *= x
x *= x
n >>= 1
return res
assert abs(Solution().myPow(2.0, 10) - 1024.0) < 1e-9
assert abs(Solution().myPow(2.1, 3) - 9.261) < 1e-9
assert abs(Solution().myPow(2.0, -2) - 0.25) < 1e-9
class Solution {
public double myPow(double x, int n) {
long e = n;
if (e < 0) { x = 1 / x; e = -e; }
double res = 1;
for (; e > 0; e >>= 1) {
if ((e & 1) == 1) res *= x;
x *= x;
}
return res;
}
}
func myPow(x float64, n int) float64 {
if n < 0 {
x, n = 1/x, -n
}
res := 1.0
for ; n > 0; n >>= 1 { // binary exponentiation
if n&1 == 1 {
res *= x
}
x *= x
}
return res
}