050.Pow(x, n) Posted on 2017-09-16 | In LeetCode Test cases1234567891011128.88023334.00515-30.0000121474836471.0000021474836471.00000-21474836482.00000-2147483648 Solution 1: TLEBrute force is not working. 1234567891011public double myPow(double x, int n) { if (n == 0) return (double)1; double result = 1; boolean neg = n < 0? true : false; n = Math.abs(n); while (n > 0) { result *= x; n--; } return neg? 1 / result : result;} Solution 2: accepted 24msBinary method. 1234567891011121314151617181920212223public double myPow(double x, int n) { if (n == 0) return (double)1; double result = 1; boolean isNegative = n < 0; if (n == Integer.MIN_VALUE) { result = x; n = Integer.MAX_VALUE; } n = n < 0? -n : n; while (n > 0) { int factor = 1; double base = x; while (n / 2 >= factor) { // n >= factor * 2 may cause overflow if n is the max or min int factor *= 2; base *= base; } result *= base; n -= factor; } return isNegative? 1 / result : result;} Alternative: accepted 20msUse long to avoid MAX and MIN checks. 1234567891011121314151617181920public double myPow(double x, int n) { if (n == 0) return (double)1; double result = 1; boolean isNegative = n < 0; long ln = (long)n; ln = ln < 0? -ln: ln; while (ln > 0) { long factor = 1; // int will cause factor = 0 (overflow) when n = MIN_VALUE double base = x; while (ln / 2 >= factor) { factor *= 2; base *= base; } result *= base; ln -= factor; } return isNegative? 1 / result : result;}