50. Pow(x, n)

50. Pow(x, n)

1、快速幂:

(1)递归解法:

(2)迭代解法:

package 数组;

public class Pow {
    public static void main(String[] args) {
        Pow pow = new Pow();
        System.out.println(pow.myPow(2, -2147483648));
        System.out.println(pow.towjinzhi(21));
    }

    // 5^7=5^3*5*3*5
    // 5^3=5*5*5
    // 5^(-7)=5^(-3)*5^(-3)*5^(-1)
    public double myPow(double x, int n) {
        // int类型的负数比整数大一位,例如:int类型的-2147483648取负,还是-2147483648
        // 因此要转成long类型的
        long N = n;
        if (n < 0) {
            return 1 / quickPow(x, -N);
        }
        return quickPow(x, N);
    }

    // 迭代的方式求
    public double quickPow(double x, long n) {
        double result = 1.0;
        double contribute = x;
        while (n > 0) {
            // 二进制位为1,计入贡献
            if (n % 2 > 0) {
                result = result * contribute;
            }
            contribute = contribute * contribute;
            n = n / 2;
        }
        return result;
    }

    // 求一个数的二进制
    public String towjinzhi(int n) {
        StringBuilder sb = new StringBuilder();
        while (n != 0) {
            sb.append(n % 2);
            n = n / 2;
        }
        return sb.reverse().toString();
    }

    // 递归的方式求
    public double quickPow1(double x, int n) {
        if (n == 0) {
            return 1;
        }
        double y = quickPow1(x, n / 2);
        if (n % 2 != 0) {
            return y * y * x;
        } else {
            return y * y;
        }
    }
}

。。

posted @ 2021-11-21 12:44  guoyu1  阅读(28)  评论(0编辑  收藏  举报