本文主要是介绍幂等运算power,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
分治思想
public static double power(double base, int exponent) {if ((equalToZero(base)) && (exponent <= 0)) {throw new IllegalArgumentException();}int positiveExponent = (exponent > 0 ? exponent : -exponent);double result = powerUnsignedExponent(base, positiveExponent);return exponent > 0 ? result : 1.0 / result;}private static boolean equalToZero(double base) {return new Double(base).equals(0.0);}private static double powerUnsignedExponent(double base,int positiveExponent) {if (positiveExponent == 0) {return 1.0;} else if (positiveExponent == 1) {return base;} else {double result = powerUnsignedExponent(base, positiveExponent >> 1);result *= result;if (isOdd(positiveExponent)) {result *= base;}return result;}}public static boolean isOdd(int value) {return (value & 0x1) != 0;}public static boolean isEven(int value) {return !isOdd(value);}
这篇关于幂等运算power的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!