50. Pow(x, n)
Description of Problem
Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).
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-2^31 <= n <= 2^31-1nis an integer.- Either
xis not zero orn > 0. -10^4<=x^n<=10^4
Solution
Explantion
The core of the problem is to consider all edge cases and remember to handle the overflow/underflow cases. The calculation can be done by "Divide and Conquer" approach.
Code (Rust)
impl Solution {
fn my_pow(x : f64, n: i32) -> f64{
match (x, n){
(0.0, _) => 0.0,
(-1.0, n) => if n % 2 == 1 {-1.0} else {1.0},
(1.0, _) | (_, 0) => 1.0,
(x, i32::MIN) => 1.0 / Self::my_pow(x, -(n+1)),
(x, n) => {
if n < 0 {
1.0 / Self::my_pow(x, -n)
}
else{
let v = Self::my_pow(x, n/2);
match (n % 2 == 0) {
true => v * v,
false => v * v * x,
}
}
}
}
}
}
Complexity
- n is the exponent
Time complexity:
- \(T(n)=O(\log(n))\)
- In general, the number of functional calls is bound by \(\log(n)\).
Auxiliary Space:
- \(S(n)=O(\log(n))\)
- Same reason as the above-mentioned.