面试题16

实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。

示例 1:

输入: 2.00000, 10
输出: 1024.00000

示例 2:

输入: 2.10000, 3
输出: 9.26100

示例 3:

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

说明:

  • -100.0 < x < 100.0

  • n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。

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

Solutions

  1. bit representation

  2. See problem 50 for details.

class Solution {
public:
    double myPow(double x, int n) {
        long N = n;
        if (N < 0) {
            x = 1.0 / x;
            N = -N;
        }

        double res = 1;
        while (N) {
            if (N & 1)
                res *= x;
            x *= x;
            N >>= 1;
        }

        return res;
    }
};
  1. fast power

class Solution {
public:
    double pow(double x, long n) {
        if (n == 1) return x;
        double half = pow(x, n >> 1);
        return n & 1 ? x * half * half : half * half;
    }
    double myPow(double x, int n) {
        if (x == 1 || x == 0) return x;
        if (n == 0) return 1;
        if (n < 0) x = 1 / x;
        // incase n == INT_MIN
        long N = abs(long(n));
        return pow(x, N);
    }
};

Last updated

Was this helpful?