标签:result 大小 double 复杂 div base style pow class
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
使用递归时间复杂度降为o(logn)n为指数大小
对cyc大佬的补充,考虑了base为零的情况,否则当base==0,exp为复数是会出错
public class Solution { public double Power(double base, int exponent) { if(Double.toString(base).equals(Double.toString(0.0))) return 1.0; if(exponent == 1) return base; boolean isNegtive = false; if(exponent < 0){ exponent = -exponent; isNegtive = true; } double result = Power(base*base, exponent/2); if(exponent % 2 !=0) result *= base; return isNegtive == false? result: 1.0/result; } }
标签:result 大小 double 复杂 div base style pow class
原文地址:https://www.cnblogs.com/tendermelon/p/12859382.html