50. Pow(x, n) Medium
1/**
2 * [50] Pow(x, n)
3 *
4 * Implement <a href="http://www.cplusplus.com/reference/valarray/pow/" target="_blank">pow(x, n)</a>, which calculates x raised to the power n (i.e., x^n).
5 *
6 * Example 1:
7 *
8 * Input: x = 2.00000, n = 10
9 * Output: 1024.00000
10 *
11 * Example 2:
12 *
13 * Input: x = 2.10000, n = 3
14 * Output: 9.26100
15 *
16 * Example 3:
17 *
18 * Input: x = 2.00000, n = -2
19 * Output: 0.25000
20 * Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25
21 *
22 *
23 * Constraints:
24 *
25 * -100.0 < x < 100.0
26 * -2^31 <= n <= 2^31-1
27 * -10^4 <= x^n <= 10^4
28 *
29 */
30pub struct Solution {}
31
32// problem: https://leetcode.com/problems/powx-n/
33// discuss: https://leetcode.com/problems/powx-n/discuss/?currentPage=1&orderBy=most_votes&query=
34
35// submission codes start here
36
37impl Solution {
38 pub fn my_pow(x: f64, n: i32) -> f64 {
39 if n == 0 {
40 return 1f64;
41 }
42 if n == 1 {
43 return x;
44 };
45 if n < 0 {
46 return 1f64 / x * Self::my_pow(1f64 / x, -n - 1);
47 }
48
49 let half = Self::my_pow(x, n / 2);
50 let result = half * half;
51 let remain = n % 2;
52
53 return if remain == 0 { result } else { result * x };
54 }
55}
56
57// submission codes end
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn test_50() {
65 assert_eq!(Solution::my_pow(2f64, 10), 1024f64);
66 assert_eq!(Solution::my_pow(2f64, -10), 1f64 / 1024f64);
67 }
68}
69
Back
© 2025 bowen.ge All Rights Reserved.