Pow(x, n)
MEDIUMDescription
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Example 1:
Input: x = 2.00000, n = 10 Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3 Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25
Constraints:
-100.0 < x < 100.0-231 <= n <= 231-1nis an integer.- Either
xis not zero orn > 0. -104 <= xn <= 104
Approaches
Checkout 3 different approaches to solve Pow(x, n). Click on different approaches to view the approach and algorithm in detail.
Brute Force using Simple Loop
This approach simulates the basic definition of exponentiation by repeatedly multiplying the base x for n times. It's the most straightforward but least efficient method.
Algorithm
- Convert the integer
nto a longNto handle theInteger.MIN_VALUEcase. - If
Nis negative, updatexto1/xandNto-N. - Initialize a variable
ansto1.0. - Iterate from
0toN-1. - In each iteration, multiply
ansbyx. - After the loop, return
ans.
The algorithm handles three main cases for the exponent n:
- Positive
n: We initialize a result to1.0and multiply it byxexactlyntimes in a loop. nis zero: By definition,x^0is1, so we return1.0.- Negative
n: We use the propertyx^-n = 1 / x^n. To avoid integer overflow whennisInteger.MIN_VALUE, we first convertnto along. Then, we can safely negate it. We calculate the power for the positive exponent-nand then take its reciprocal. A small optimization for the negative case is to compute(1/x)^-ninstead.
public class Solution {
public double myPow(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
double ans = 1.0;
for (long i = 0; i < N; i++) {
ans = ans * x;
}
return ans;
}
}
Complexity Analysis
Pros and Cons
- Very simple to understand and implement.
- Works correctly for small values of
n.
- Extremely inefficient for large values of
n. - Will result in a 'Time Limit Exceeded' (TLE) error on most online judges due to the O(n) complexity.
Code Solutions
Checking out 5 solutions in different languages for Pow(x, n). Click on different languages to view the code.
public class Solution {
public double MyPow(double x, int n) {
return n >= 0 ? qpow(x, n) : 1.0 / qpow(x, -(long) n);
}
private double qpow(double a, long n) {
double ans = 1;
for (; n > 0; n >>= 1) {
if ((n & 1) == 1) {
ans *= a;
}
a *= a;
}
return ans;
}
}Video Solution
Watch the video walkthrough for Pow(x, n)
Similar Questions
5 related questions you might find useful
Patterns:
Companies:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.