本问题对应的 leetcode 原文链接:剑指 Offer 16. 数值的整数次方

问题描述

实现 pow(x, n) ,即计算 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

解题思路

视频讲解直达: 本题视频讲解

代码实现

class Solution {
    public double myPow(double x, int n) {
        double res = 1;
        long y = n;
        if(n < 0){
            y = -y;
            x = 1 / x;
        }
        while(y > 0){
            if(y % 2 == 1){
                res = res * x;
            }

            x = x * x;
            y = y / 2;
        }
        return res;
    }
}

时间复杂度:O(logn)
空间复杂度:O(1)

Python

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        res = 1
        y = n
        if n < 0:
            y = -y
            x = 1 / x
        while y > 0:
            if y % 2 == 1:
                res = res * x
            x = x * x
            y = y // 2
        return res


C++

class Solution {
public:
    double myPow(double x, int n) {
        double res = 1;
        long y = n;
        if (n < 0) {
            y = -y;
            x = 1 / x;
        }
        while (y > 0) {
            if (y % 2 == 1) {
                res = res * x;
            }
            x = x * x;
            y = y / 2;
        }
        return res;
    }
};


Go

func myPow(x float64, n int) float64 {
    res := 1.0
    y := int64(n)
    if n < 0 {
        y = -y
        x = 1 / x
    }
    for y > 0 {
        if y % 2 == 1 {
            res *= x
        }
        x *= x
        y /= 2
    }
    return res
}


JS

var myPow = function(x, n) {
    let res = 1;
    let y = n;
    if (n < 0) {
        y = -y;
        x = 1 / x;
    }
    while (y > 0) {
        if (y % 2 === 1) {
            res = res * x;
        }
        x = x * x;
        y = Math.floor(y / 2);
    }
    return res;
};


发表回复

后才能评论