题目链接:https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&&tqId=11165&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

  思路一:当指数不为负数的时候,我们直接计算即可。当指数为负数的时候我们可以对其进行一个变形 ,这样我们直接进行遍历计算即可。

import java.util.*;
public class Solution {
    public double Power(double base, int exponent) {
        if(exponent < 0) {
            exponent = -exponent;
            base = 1.0 / base;
        }
        double ans = 1.0;
        for(int i = 1; i <= exponent; ++ i) {
            ans *= base;
        }
        return ans;
    }
}

  思路二:按照上述思路,我们可以使用 Java 中 Math 函数来进行求解。

import java.util.*;
public class Solution {
    public double Power(double base, int exponent) {
        if(exponent > 0) return Math.pow(base, exponent);
        else if(exponent == 0) return 1;
        else return Math.pow(1.0 / base, -exponent);
    }
}

  思路三:快速幂:https://blog.nowcoder.net/n/f93bed69e38f474a839cb5105d0babc2

import java.util.*;
public class Solution {
    public double Power(double base, int exponent) {
        if(exponent < 0) {
            exponent = -exponent;
            base = 1.0 / base;
        }
        return quickPow(base, exponent);
    }
    public static double quickPow(double a, int b) {
        double ans = 1.0, res = a;
        while(b > 0) {
            if((b & 1) != 0) ans = ans * res;
            res = res * res;
            b >>= 1;
        }
        return ans;
    }
}