leetcode

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

commit 8f24c825bc456233bcbee864de5798831afb5c95
parent 07b55b095620042e1cdb72094af3ffd2587f35f2
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date:   Fri, 23 Aug 2024 21:13:57 +0200

Daily Problem

Diffstat:
AProblems/0592.cpp | 39+++++++++++++++++++++++++++++++++++++++
MREADME.md | 1+
2 files changed, 40 insertions(+), 0 deletions(-)

diff --git a/Problems/0592.cpp b/Problems/0592.cpp @@ -0,0 +1,39 @@ +class Solution { + public: + string fractionAddition(const string &expression) const { + const int n = size(expression); + int numerator = 0, denominator = 1; + + for (int i = 0; i < n;) { + int sign = 1; + if (expression[i] == '+' || expression[i] == '-') { + if (expression[i] == '-') sign = -1; + i++; + } + + int num = 0; + while (i < n && isdigit(expression[i])) { + num = num * 10 + (expression[i] - '0'); + i++; + } + num *= sign; + + i++; + + int den = 0; + while (i < n && isdigit(expression[i])) { + den = den * 10 + (expression[i] - '0'); + i++; + } + + numerator = numerator * den + num * denominator; + denominator *= den; + + int gcdVal = gcd(abs(numerator), denominator); + numerator /= gcdVal; + denominator /= gcdVal; + } + + return to_string(numerator) + "/" + to_string(denominator); + } +}; diff --git a/README.md b/README.md @@ -412,6 +412,7 @@ for solving problems. | 0586 | Easy | [Customer Placing the Largest Number of Orders](Problems/0586.cpp) | | 0589 | Easy | [N-ary Tree Preorder Traversal](Problems/0589.cpp) | | 0590 | Easy | [N-ary Tree Postorder Traversal](Problems/0590.cpp) | +| 0592 | Medium | [Fraction Addition and Subtraction](Problems/0592.cpp) | | 0595 | Easy | [Big Countries](Problems/0595.cpp) | | 0596 | Easy | [Classes More Than 5 Students](Problems/0596.cpp) | | 0601 | Hard | [Human Traffic of Stadium](Problems/0601.cpp) |