Pow(x, n)

Implement pow(xn).

可以直接调用api

1 public class Solution {
2     public double pow(double x, int n) {
3         return Math.pow(x, n);
4     }
5 }

这道题其实和Divide Two Integers有点像

思路也是一样的,直接用2 ^ n次方递增

需要考虑n为负的情况

 1 public class Solution {
 2     public double pow(double x, int n) {
 3         double result = 1;      
 4         boolean isNeg = false;
 5         if(n < 0)
 6             isNeg = true;
 7         n = Math.abs(n);
 8         
 9         while(n > 0){
10             long tempCount = 1;
11             double tempResult = 1;
12             tempResult *= x;
13             
14             while(tempCount * 2 <= n){
15                 tempResult *= tempResult;
16                 tempCount += tempCount;
17             }//while
18             n -= tempCount;
19             result *= tempResult;
20         }
21         if(isNeg)
22             result = 1 / result;
23         return result;
24     }
25 }

 

posted on 2015-01-21 15:45  luckygxf  阅读(225)  评论(0编辑  收藏  举报

导航