数值的整数次方

题目描述

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
 
保证base和exponent不同时为0
 
 1 public class Solution {
 2     public double cal(double base, int exp) {
 3         if (exp == 0) return 1;
 4         if (exp == 1) return base;
 5         double ans = cal(base, exp >> 1);
 6         ans = ans * ans;
 7         if (exp % 2 == 1) {
 8             ans = ans * base;
 9         }
10         
11         return ans;
12             
13         
14     }
15     public double Power(double base, int exponent) {
16         if (base == 0) return 0;
17         int exp = exponent;
18         if (exponent < 0) exp = exp * -1;
19         double ans = cal(base, exp);
20         if (exponent < 0) {
21             ans = 1 / ans;
22         }
23         
24         return ans;
25         
26   }
27 }

 

posted @ 2020-02-13 22:33  hyx1  阅读(109)  评论(0编辑  收藏  举报