From 88d29872f974da2d93e87ec7fe9d9f223c8811cd Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Tue, 24 Jan 2023 09:06:49 +0400 Subject: [PATCH] feat: add LeetCode Pow(x, n) (#1194) * add leetcode Pow(x, n) * Update 50.c fix comment * Update 50.c simplification * add lower_bound const. * updating DIRECTORY.md Co-authored-by: David Leal Co-authored-by: github-actions[bot] --- leetcode/DIRECTORY.md | 1 + leetcode/src/50.c | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 leetcode/src/50.c 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); +}