Implement pow(x, n).
题解:注意两点:
代码如下:
1 public class Solution { 2 public double pow(double x, int n) { 3 if(n == 0) 4 return 1; 5 if(n == 1) 6 return x; 7 8 boolean isNeg = false; 9 10 //if n is negative,we first caculate 1/pow(x,n) = pow(x,-n) 11 if(n<0){ 12 isNeg = true; 13 n *= -1; 14 } 15 16 //binary 17 int mid = n /2; 18 int left = n - mid*2; 19 double front = pow(x, mid); 20 double end = pow(x, left); 21 22 if(isNeg) 23 return 1/(front*front*end); 24 else { 25 return front*front*end; 26 } 27 } 28 }
【leetcode刷题笔记】Pow(x, n),布布扣,bubuko.com
原文地址:http://www.cnblogs.com/sunshineatnoon/p/3856165.html