#50
Medium Algorithms Powx n
Math Recursion
38.3% acceptance
Jan 12, 2026
11575
10520
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn my_pow(x: f64, n: i32) -> f64 {
if n == 0 {
return 1.0;
}
// Handle negative power
let (mut base, mut exp) = if n < 0 {
(1.0 / x, -(n as i64))
} else {
(x, n as i64)
};
let mut result = 1.0;
// Fast exponentiation using binary method
while exp > 0 {
if exp % 2 == 1 {
result *= base;
}
base *= base;
exp /= 2;
}
result
}
}