LeetCode毎日1題[49]数値の整数次方

1631 ワード

LeetCode値の整数次数[中等]
関数double Power(double base,int exponent)を実現して、baseのexponentの次数を求めます.ライブラリ関数は使用できませんが、大きな数の問題を考慮する必要はありません.
ソース:力ボタン(LeetCode)リンク:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof
例1:
入力:2.0000、10出力:1024.00000
例2:
入力:2.10000、3出力:9.26100
例3:
入力:2.0000、-2出力:0.25,000解釈:2-2=1/22=1/4=0.25
テーマ分析
解法1
再帰実装を用いて型抜き2を行い、結果を返す
解法2
すべて正のべき乗に変換して解きます.私は直接リンクを置くことが分かりません.https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/mian-shi-ti-16-shu-zhi-de-zheng-shu-ci-fang-kuai-s/
コード実装
public class MyPow {
    public static void main(String[] args) {
        System.out.println(myPow2(34.00515, -3));
        System.out.println(myPow2(2.0000, -2));
        System.out.println(myPow3(34.00515, -3));
        System.out.println(myPow3(2.0000, -2));
    }

    public static double myPow3(double x, int n) {
        if (x == 0) {
            return 1;
        }
        long b = n;
        double res = 1.0;
        if (b < 0) {
            x = 1 / x;
            b = -b;
        }
        while (b > 0) {
            if ((b & 1) == 1) {
                res *= x;
            }
            x *= x;
            b >>= 1;
        }
        return res;
    }

    public static double myPow2(double x, int n) {
        if (n == 0) {
            return 1;
        }
        if (n == 1) {
            return x;
        }
        if (n == -1) {
            return 1 / x;
        }
        double half = myPow2(x, n / 2);
        double mod = myPow2(x, n % 2);
        return half * half * mod;
    }
}