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 <halfpacho@gmail.com>
Co-authored-by: github-actions[bot] <github-actions@users.noreply.github.com>
This commit is contained in:
Alexander Pantyukhin 2023-01-24 09:06:49 +04:00 committed by GitHub
parent 90d7d81807
commit 88d29872f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 0 deletions

View File

@ -30,6 +30,7 @@
| 37 | [Sudoku Solver](https://leetcode.com/problems/sudoku-solver) | [C](./src/37.c) | Hard | | 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 | | 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 | | 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 | | 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 | | 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 | | 63 | [Unique Paths II](https://leetcode.com/problems/unique-paths-ii) | [C](./src/63.c) | Medium |

39
leetcode/src/50.c Normal file
View File

@ -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);
}