Implement pow(x, n).
double sum = 1; if (n > 0) { while ((n--) > 0) sum *= x; return sum; } else if (n < 0) { while ((n++) < 0) sum /= x; } return sum; //开始单纯的我是这样写的。超时了
if (n == 0) //想了一下,不就是求x+10000/x的最小值。自己运行都通过了,但是leetcode仍然显示超时,错误1,x的100次仍然很大,需要bigdeciml。错误2,前后两步运行时间是相差很大的,所以不是求x+10000/x的最小值。AC版的才是正确答案 return 1; double sum = 1, tmp = 1; if (n > 0) { int sq = (int) Math.round(Math.sqrt(n)); for (int i = sq; i > 0; i--) tmp *= x; // System.out.println(tmp); for (int i = 0; i < sq; i++) sum *= tmp; int i = n - sq * sq; // System.out.println(i); if (i > 0) { for (int j = 0; j < i; j++) sum *= x; } else if (i < 0) { for (int j = i; j < 0; j++) sum /= x; } return sum; } else { int m = Math.abs(n); int sq = (int) Math.round(Math.sqrt(m)); for (int i = sq; i > 0; i--) tmp /= x; // System.out.println("tmp="+tmp); for (int i = 0; i < sq; i++) sum *= tmp; int i = n + sq * sq; // System.out.println(i); if (i > 0) { for (int j = 0; j < i; j++) sum *= x; } else if (i < 0) { for (int j = i; j < 0; j++) sum /= x; } return sum; }
public class Solution { //虽然用了递归,挺巧妙的,一定要记得思想 & 和 >> public double myPow(double x, int n) { //类似思想的还有求最大公约数 if (n == 0) return 1.0; if (n < 0) { x = 1 / x; n = ~n + 1; } if (n == 1) return x; if (n == 2) return x * x; if ((n & 1) == 1) return x * myPow(x * x, n >> 1); return myPow(x * x, n >> 1); } }