Skip to content

Latest commit

 

History

History
181 lines (147 loc) · 3.24 KB

File metadata and controls

181 lines (147 loc) · 3.24 KB

题目描述

实现 pow(xn) ,即计算 x 的 n 次幂函数(即,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

 

注意:本题与主站 50 题相同:https://leetcode.cn/problems/powx-n/

解法

Python3

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0:
            return 1
        if n == 1:
            return x
        if n == -1:
            return 1 / x
        half = self.myPow(x, n // 2)
        return half * half * self.myPow(x, n % 2)

Java

class Solution {
    public double myPow(double x, int n) {
        if (n == 0) return 1;
        if (n == 1) return x;
        if (n == -1) return 1 / x;
        double half = myPow(x, n / 2);
        return half * half * myPow(x, n % 2);
    }
}

JavaScript

/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
var myPow = function (x, n) {
    let r = 1;
    let tmp = x;
    let tag = 0;
    if (n < 0) {
        tag = 1;
        n = -n;
    }
    while (n) {
        if (n & 1) {
            r *= tmp;
        }
        tmp *= tmp;
        n >>>= 1;
    }
    return tag ? 1 / r : r;
};

Go

func myPow(x float64, n int) float64 {
    p := abs(n)
    res := 1.0
    for p != 0 {
        if p&1 == 1 {
            res *= x
        }
        x *= x
        p = p >>1
    }
    if n < 0 {
        return 1/res
    }
    return res
}

func abs(x int) int {
    if x > 0 {
        return x
    }
    return -x
}

C++

class Solution {
public:
    double myPow(double x, int n) {
        long m = n;
        if (m < 0) {
            x = 1 / x;
            m = -m;
        }
        double ans = 1;
        while (m) {
            if (m & 1) {
                ans *= x;
            }
            x *= x;
            m >>= 1;
        }
        return ans;
    }
};

C#

public class Solution {
    public double MyPow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        if (n == 1) {
            return x;
        }
        if (n == -1) {
            return 1 / x;
        }
        double half = MyPow(x, n / 2);
        return half * half * MyPow(x, n % 2);
    }
}

...