就是求x的n次方 x^n = x^(n/2) * x^(n/2)*x^(n%2)
如果n< 0 最后结果应该是1/result
public class Solution { public double myPow(double x, int n) { if (n == 0) { return 1.0; } if (n == 1) { return x; } boolean isneg = n < 0; if (isneg) { n *= -1; } double res = myPow(x, n/2); double result; if (n % 2 == 0) { result = res* res; } else { result = res * res * x; } if (isneg) { return 1/result; } else { return result; } } }
没有评论:
发表评论