[LeetCode] 50. Pow(x, n)
Implement pow(x, n).
Time complexity: O(logn).
Thought process:
Shortest problem description!
Recursively calculate pow(x, n / 2). Base cases:
- n = 0, return 1.
- n = 1, return x.
- n = -1, return 1 / x.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class Solution { public double myPow(double x, int n) { if (n == 0) { return 1; } if (n == 1) { return x; } if (n == -1) { return 1 / x; } if (n % 2 == 0) { double half = myPow(x, n / 2); return half * half; } if (n < 0) { return myPow(x, n / 2) * myPow(x, n / 2 - 1); } return myPow(x, n / 2) * myPow(x, n / 2 + 1); } } |
Time complexity: O(logn).
Comments
Post a Comment