Skip to content

Latest commit

 

History

History
112 lines (82 loc) · 2.33 KB

File metadata and controls

112 lines (82 loc) · 2.33 KB

English Version

题目描述

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

 

示例 1:

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

示例 2:

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

示例 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

解法

Python3

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0:
            return 1
        if n < 0:
            return 1 / self.myPow(x, -n)
        y = self.myPow(x, n >> 1)
        return y * y if (n & 1) == 0 else y * y * x

Java

class Solution {
    public double myPow(double x, int n) {
        long N = n;
        return N >= 0 ? pow(x, N) : 1.0 / pow(x, -N);
    }

    public double pow(double x, long N) {
        if (N == 0) {
            return 1.0;
        }
        double y = pow(x, N >> 1);
        return (N & 1) == 0 ? y * y : y * y * x;
    }
}

TypeScript

function myPow(x: number, n: number): number {
    let res = 1;
    if (n < 0) {
        n = -n;
        x = 1 / x;
    }
    for (let i = n; i != 0; i = Math.floor(i / 2)) {
        if ((i & 1) == 1) {
            res *= x;
        }
        x *= x;
    }
    return res;
}

...