commit af0d37d72a902e65b341d68f566217e8a1b31f53
parent 659dacbd46c522ad0a0f54cc27a793197dd7c7ef
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date: Tue, 19 Nov 2024 20:55:41 +0100
1 Random Problem
Diffstat:
2 files changed, 35 insertions(+), 0 deletions(-)
diff --git a/Problems/0640.cpp b/Problems/0640.cpp
@@ -0,0 +1,34 @@
+class Solution {
+ static pair<int, int> count(const string_view &s) {
+ int x = 0, nums = 0, sign = 1;
+ for (int i = 0; i < size(s); i++) {
+ if (s[i] == '+')
+ sign = 1;
+ else if (s[i] == '-')
+ sign = -1;
+ else {
+ int num = s[i] == 'x' ? 1 : 0;
+ while (isdigit(s[i]))
+ num = num * 10 + s[i++] - '0';
+ if (s[i] == 'x')
+ x += sign * num;
+ else
+ nums += sign * num, i--;
+ }
+ }
+
+ return {x, nums};
+ }
+
+ public:
+ string solveEquation(const string &equation) const {
+ const string_view sv(equation);
+ const auto it = sv.find('=');
+
+ const auto [lx, ln] = count({begin(sv), it});
+ const auto [rx, rn] = count(sv.substr(it + 1));
+
+ if (lx == rx) return ln == rn ? "Infinite solutions" : "No solution";
+ return "x=" + to_string((rn - ln) / (lx - rx));
+ }
+};
diff --git a/README.md b/README.md
@@ -501,6 +501,7 @@ reference and a base for solving problems.
| 0636 | Medium | [Exclusive Time of Functions](Problems/0636.cpp) |
| 0637 | Easy | [Average of Levels in Binary Tree](Problems/0637.cpp) |
| 0638 | Medium | [Shopping Offers](Problems/0638.cpp) |
+| 0640 | Medium | [Solve the Equation](Problems/0640.cpp) |
| 0641 | Medium | [Design Circular Deque](Problems/0641.cpp) |
| 0643 | Easy | [Maximum Average Subarray I](Problems/0643.cpp) |
| 0645 | Easy | [Set Mismatch](Problems/0645.cpp) |