Sword refers to offer 16. The integer power of the value

Sword refers to offer 16. The integer power of the value

Title description

Insert picture description here

Problem-solving ideas

The difficulty of this question is to consider various boundary conditions.
Insert picture description here


Note, why use the long type for exponents of fast powers?

Because the range of int is [-2^31,2^31-1], the range of negative numbers is larger than that of positive numbers, so you cannot simply take the absolute value. If the base is exactly -2^31 and the exponent is of type int, it will overflow.


To compare double variables for equality, do not use "==", or use the equals method to convert to a string, or the two double variables are reduced to one error (such as 1e-6) as here.


class Solution {
    
    
    public double myPow(double x, int n) {
    
    
        long N = n;
        //底数为0,指数小于0,则非法
        if (isEqual(x, 0.0) && N < 0) return 0.0;
        //底数为0,指数大于等于0,直接返回0.0
        if (isEqual(x, 0.0) && N >= 0) return 0.0;
        
        return N >= 0 ? quickPow(x, N) : 1.0 / quickPow(x, -N);
        
    }

    //快速幂模板, 注意指数 exponent 是 long 类型防止溢出,且为非负数
    public double quickPow(double base, long exponent) {
    
    
        if (exponent == 0) return 1;
        if (exponent == 1) return base;

        double res = quickPow(base, exponent >> 1);
        res *= res;
        //如果是奇数,则要额外乘上base
        if ((exponent & 0x01) == 1)
            res *= base;
        return res;
    }

    //判断两个 double 变量是否相等
    public boolean isEqual(double a, double b) {
    
    
        return Math.abs(a - b) < 1e-6;
    }
}

Guess you like

Origin blog.csdn.net/cys975900334/article/details/114837868