Pow(x, n)
Implement pow(x, n).
1 public class Solution { 2 private double power(double x, int n) { 3 if (n == 0) 4 return 1; 5 double v = power(x, n / 2); 6 if (n % 2 == 0) { 7 return v * v; 8 } else { 9 return v * v * x; 10 } 11 } 12 13 public double pow(double x, int n) { 14 if (n < 0) { 15 return 1 / power(x, -n); 16 } else { 17 return power(x, n); 18 } 19 } 20 }