640. Solve the Equation
Explanation
To solve this problem, we need to parse the equation and separate the coefficients of x
and the constants on both sides of the equation. Then we simplify the equation by moving all x
terms to one side and all constant terms to the other side. Finally, we calculate the value of x
and handle cases where there are no solutions or infinite solutions.
Here is the step-by-step algorithm:
- Parse the equation to separate coefficients of
x
and constants on both sides. - Simplify the equation by moving all
x
terms to one side and all constant terms to the other side. - Calculate the value of
x
. - Handle cases where there are no solutions or infinite solutions.
Time complexity: O(n) where n is the length of the equation.
Space complexity: O(1)
class Solution {
public String solveEquation(String equation) {
int xCoeff = 0, constant = 0;
int sign = 1;
int n = equation.length();
int i = 0;
while (i < n) {
int j = i + 1;
while (j < n && equation.charAt(j) != '+' && equation.charAt(j) != '-') {
j++;
}
String term = equation.substring(i, j);
if (term.contains("x")) {
if (term.equals("x") || term.equals("+x")) {
xCoeff += sign;
} else if (term.equals("-x")) {
xCoeff -= sign;
} else {
xCoeff += sign * Integer.parseInt(term.substring(0, term.length() - 1));
}
} else {
constant += sign * Integer.parseInt(term);
}
if (j < n && equation.charAt(j) == '-') {
sign = -1;
} else {
sign = 1;
}
i = j + 1;
}
if (xCoeff == 0) {
if (constant == 0) {
return "Infinite solutions";
} else {
return "No solution";
}
} else {
return "x=" + (-constant / xCoeff);
}
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.