Skip to content

Latest commit

 

History

History
103 lines (79 loc) · 2.15 KB

README_EN.md

File metadata and controls

103 lines (79 loc) · 2.15 KB

中文文档

Description

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

 

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
  • -231 <= n <= 231-1
  • n is an integer.
  • -104 <= xn <= 104

Solutions

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;
}

...