求數值的整數次方

需要考慮的特殊情況:

  1. 輸入的指數是0或負數
  2. 底數是0

一般的算法當指數爲32時,需要在循環中做31次乘法,換種思路,在平方基礎上求4次方,4次方基礎上求8次方,利用遞歸可以減少乘法運算次數

package tao.leetcode;
/**
 * Created by Tao on 2017/7/30.
 */
public class MyLeetcode {
    public static void main(String[] args) {
        double base = 3;
        int exp = 5;
        double res = Power(base,exp);
        System.out.println(res);
    }

    private static double Power(double base, int exp) {
        if (equals(base,0.0)) {
            return 0.0;
        }
        if (exp < 0) {
            base = 1 / base;
            exp = -exp;
        }
        double result = PowerExp(base,exp);
        return result;
    }

    private static double PowerExp(double base, int exp) {
        if (exp == 0) {
            return 1;
        }
        if (exp == 1) {
            return base;
        }
        double res = PowerExp(base,exp>>1);
        res *= res;
        if ((exp & 1) == 1) {
            res *= base;
        }
        return res;
    }

    private static boolean equals(double base, double v) {
        if ((base-v > 0.0000001) || (base-v < -0.0000001)) {
            return false;
        } else {
            return true;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章