Implement pow(x, n).

Example 1:

Input: 2.00000, 10  Output: 1024.00000

Example 2:

Input: 2.10000, 3   Output: 9.26100
package medium;

public class L50MyPow {
    // 调用Math.pow() 函数
    public double mypow(double x, int n) {
        double nn = n;
        return Math.pow(x, nn);
    }

    //本题就x的n次方,如求2的4次方。可以4个2相乘,也可以先两个2相乘,之后两个4在相乘。
    public double myPow(double x, int n) {
        //防止n越界2147483647,用long类型的N来代替n
        long N = n;
        double result = 1.0;
        // double类型的x 判断x是否为0
        if ((x - 0.0 < -0.000000000001) && n < 0) {
            return 0.0;
        }
        //指数小于零,求得的数是用负指数相反数求得的值的倒数。
        if (N < 0) {
            N = -N;
            x = 1 / x;
        }
        double current_product = x;
        for (long i = N; i > 0; i /= 2) {
            if ((i % 2) == 1) {
                result = result * current_product;
            }
            current_product = current_product * current_product;
        }
        return result;
    }

    public static void main(String[] args) {
        L50MyPow cc = new L50MyPow();
        //测试负数的整数次方。  4.0
        System.out.println(cc.myPow(-2, 2));
        System.out.println("!!!!!!!!!!!!!!!!!!!");
        //小数的负数次方   2.543114507074558E-5
        double re = cc.myPow(34.00515, -3);
        System.out.println(re);
        //小数的大正整数次方次方 0.0
        System.out.println(cc.myPow(0.00001, 2147483647));
    }
}

 

分类:

技术点:

相关文章:

相关资源