题解 | #数值的整数次方#
数值的整数次方
http://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00
/** * @author jingbu * * 数值的整数次方 * 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。 */ public class Main { public static void main(String[] args) { } } class Solution { public double Power(double base, int exponent) { //如果exponent小于0,用1除以正数的值 return exponent<0?1/dfs(base,-exponent):dfs(base,exponent); } //一直递归到exponent为0 public double dfs(double base, int exponent){ if(exponent==0){ return 1; } double y=dfs(base,exponent/2); return exponent%2==0?y*y:y*y*base; } }