leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

commit bd226acde6fe111626dd2dcede6643b41314ae06
parent 8fb057d53b1d104444a79dbcf58e0d4e1ce5d839
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date:   Sat,  1 Apr 2023 13:32:36 +0200

Random Problem

Diffstat:
AProblems/0029.cpp | 35+++++++++++++++++++++++++++++++++++
MREADME.md | 1+
2 files changed, 36 insertions(+), 0 deletions(-)

diff --git a/Problems/0029.cpp b/Problems/0029.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int divide(int dividend, int divisor) { + if (divisor == INT_MIN) return dividend == INT_MIN; + if (divisor == INT_MAX) { + if (dividend == INT_MIN) return -1; + if (dividend == INT_MAX) return 1; + return 0; + } + + if (divisor == 1) return dividend; + if (divisor == -1) { + if (dividend == INT_MIN) return INT_MAX; + return -dividend; + } + + int res = 0, sign = 1; + if (divisor < 0) divisor = -divisor, sign = -sign; + if (dividend < 0) { + if (dividend == INT_MIN) dividend += divisor, res++; + dividend = -dividend, sign = -sign; + } + + while (dividend >= divisor) { + long temp = divisor, count = 1; + while (temp << 1 <= dividend) { + temp <<= 1; + count <<= 1; + } + dividend -= temp; + res += count; + } + return sign * res; + } +}; diff --git a/README.md b/README.md @@ -50,6 +50,7 @@ for solving problems. | 0026 | Easy | [Remove Duplicates from Sorted Array](Problems/0026.cpp) | | 0027 | Easy | [Remove Element](Problems/0027.cpp) | | 0028 | Medium | [Find the Index of the First Occurrence in a String](Problems/0028.cpp) | +| 0029 | Medium | [Divide Two Integers](Problems/0029.cpp) | | 0033 | Medium | [Search in Rotated Sorted Array](Problems/0033.cpp) | | 0034 | Medium | [Find First and Last Position of Element in Sorted Array](Problems/0034.cpp) | | 0035 | Easy | [Search Insert Position](Problems/0035.cpp) |