数值的整数次方

题目描述

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

一:通过迭代乘积的方式

 1 public class Solution {
 2 
 3     public double Power(double base, int exponent) {
 4 
 5         double res = 1;
 6         int t = Math.abs(exponent);
 7         for (int i = 0; i < t; i++) {
 8             res *= base;
 9 
10         }
11 
12         if (base == 0) {
13             return 0;
14 
15         } else {
16             if (exponent < 0)
17                 res = 1 / res;
18         }
19         return res;
20     }

二:通过快速幂方法

快速幂就是快速算底数的n次幂。其时间复杂度为 O(log₂N), 与朴素的O(N)相比效率有了极大的提高。(注意:在百科里给的需要根据题意有所调整)

 1 public class Solution {
 2 
 3     public double Power(double base, int exponent) {
 4 
 5         double res = 1;
 6 
 7         int p = Math.abs(exponent);  //需要判断负指数
 8 
 9         while (p != 0) {
10 
11             if ((p & 1) != 0) {
12 
13                 res *= base;
14 
15             }
16             base *= base;
17             p >>= 1;
18         }
19 
20         return exponent < 0 ? 1 / res : res;  //不要忘记这里判断的是exponent而不是绝对值量
21 
22     }}

 

posted @ 2018-08-06 19:35  Octopus22  阅读(99)  评论(0编辑  收藏  举报