diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 5fee0e8a..eea7a8ef 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -30,6 +30,7 @@ | 37 | [Sudoku Solver](https://leetcode.com/problems/sudoku-solver) | [C](./src/37.c) | Hard | | 38 | [Count and Say](https://leetcode.com/problems/count-and-say) | [C](./src/38.c) | Medium | | 42 | [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water) | [C](./src/42.c) | Hard | +| 50 | [Pow(x, n)](https://leetcode.com/problems/powx-n) | [C](./src/50.c) | Medium | | 53 | [Maximum Subarray](https://leetcode.com/problems/maximum-subarray) | [C](./src/53.c) | Medium | | 62 | [Unique Paths](https://leetcode.com/problems/unique-paths) | [C](./src/62.c) | Medium | | 63 | [Unique Paths II](https://leetcode.com/problems/unique-paths-ii) | [C](./src/63.c) | Medium | diff --git a/leetcode/src/50.c b/leetcode/src/50.c new file mode 100644 index 00000000..1e539e04 --- /dev/null +++ b/leetcode/src/50.c @@ -0,0 +1,39 @@ +double powPositive(double x, int n){ + if (n == 1){ + return x; + } + + double val = powPositive(x, n / 2); + double result = val * val; + + // if n is odd + if (n & 1 > 0){ + result *= x; + } + + return result; +} + +// Divide and conquer. +// Runtime: O(log(n)) +// Space: O(1) +double myPow(double x, int n){ + if (n == 0){ + return 1; + } + + const int LOWER_BOUND = -2147483648; + + // n is the minimum int, couldn't be converted in -n because maximum is 2147483647. + // this case we use (1 / pow(x, -(n + 1))) * n + if (n == LOWER_BOUND){ + return 1 / (powPositive(x, -(n + 1)) * x); + } + + // 1 / pow(x, -(n + 1)) + if (n < 0){ + return 1 / powPositive(x, -n); + } + + return powPositive(x, n); +}