Leetcode 640. Solve the Equation
The problem is to solve a linear equation represented as a string equation
. The equation contains one variable x
and is in the format of ax + b = cx + d
. Here a
, b
, c
, and d
are integers (they can be positive, negative or zero). The goal is to find the value of x
.
When parsing the equation, note:
=
to represent the equality.x
.Output either the solution, “No solution” if the equation has no solution, or “Infinite solutions” if the equation has infinitely many solutions.
x
?
x
.=
sign.x
and the constants.x
and constants.ax + b = 0
form.x
equals zero:
x
and output it in the required format.#include <iostream>
#include <sstream>
using namespace std;
pair<int, int> parseEquationSide(const string& side) {
int coefficient = 0, constant = 0;
int sign = 1; // for the leading sign
int num = 0;
bool numStarted = false;
for (size_t i = 0; i < side.size(); ++i) {
char c = side[i];
if (isdigit(c)) {
numStarted = true;
num = num * 10 + (c - '0');
} else if (c == 'x') {
// When x is directly prefixed by a digit, complete the number read so far
if (!numStarted) num = 1;
coefficient += sign * num;
numStarted = false;
num = 0;
} else if (c == '+' || c == '-') {
// Complete the previous number if any
if (numStarted) {
constant += sign * num;
numStarted = false;
num = 0;
}
// Update the sign for the next number/x
sign = (c == '-') ? -1 : 1;
}
}
// If a number was in progress at the end
if (numStarted) constant += sign * num;
return {coefficient, constant};
}
string solveEquation(string equation) {
size_t pos = equation.find('=');
string left = equation.substr(0, pos);
string right = equation.substr(pos + 1);
// Parse both sides
auto leftResult = parseEquationSide(left);
auto rightResult = parseEquationSide(right);
// Left: ax + b, Right: cx + d
int coefficient = leftResult.first - rightResult.first;
int constant = rightResult.second - leftResult.second;
if (coefficient == 0) {
if (constant == 0) return "Infinite solutions";
else return "No solution";
}
int x = constant / coefficient;
return "x=" + to_string(x);
}
int main() {
string equation = "2x+3x-6x=x+2";
cout << solveEquation(equation) << endl;
return 0;
}
The time complexity for parsing and solving the equation is O(n), where n is the length of the input string. The operations include parsing the string and performing constant-time arithmetic, both of which are linear concerning the input string length.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?