Pow(x, n)

Pow(x, n)

CategoryDifficultyLikesDislikes
algorithmsMedium (37.83%)944-

Tags

math | binary-search

Companies

bloomberg | facebook | google | linkedin

实现  pow(xn) ,即计算  x  的  n  次幂函数(即,xn )。

示例 1:

1
2
输入:x = 2.00000, n = 10
输出:1024.00000

示例 2:

1
2
输入:x = 2.10000, n = 3
输出:9.26100

示例 3:

1
2
3
输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25

提示:

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • -104 <= xn <= 104

Discussion | Solution

解法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

struct Solution;

// @lc code=start
impl Solution {
    /// ## 解题思路
    /// - 二分
    pub fn my_pow(x: f64, n: i32) -> f64 {
        match (x, n) {
            (_, 1) => x,
            (_, 0) => 1.0,
            (1.0, _) => 1.0,
            (-1.0, _) => if n % 2 == 0 { 1.0 } else { -1.0 },
            _ => {
                let mut m = n.abs() as u32;
                let mut x = x;
                let mut res = 1.0;
                while m > 0 {
                    if m %2 != 0 {
                        res *= x;
                    }
                    x *= x;
                    m /= 2;
                }

                if n < 0 {
                    1.0/res
                } else {
                    res
                }
            }
        }
    }
}
// @lc code=end
// @lc code=end


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
    /**
    * ## 解题思路
    * *
    * * f(n) = f(n/2) * f(n/2) * f(n%2)
    */
    double myPow(double x, int n) {
        // x == 0
        if (x <= 0.00001 && x >= -0.00001) {
            return 0;
        }
        // x == 1
        if ((x-1<=0.000001 && x-1>=-0.000001)) {
            return 1;
        }
        // x == -1
        if ((x+1<=0.000001 && x+1>=-0.000001)) {
            return n %2?-1:1;
        }
        if (n == -2147483648) {
            return 0;
        }
        if (n<0) {
            return 1 / myPow(x, -n);
        }
        if (n==0) {
            return 1;
        }
        if (n==1) {
            return x;
        }
        return myPow(x, n/2) * myPow(x, n/2) * myPow(x, n%2);
    }
};
updatedupdated2024-08-252024-08-25