Algorithm


Problem Name: 640. Solve the Equation

Solve a given equation and return the value of 'x' in the form of a string "x=#value". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return "No solution" if there is no solution for the equation, or "Infinite solutions" if there are infinite solutions for the equation.

If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.

 

Example 1:

Input: equation = "x+5-3+x=6+x-2"
Output: "x=2"

Example 2:

Input: equation = "x=x"
Output: "Infinite solutions"

Example 3:

Input: equation = "2x=x"
Output: "x=0"

 

Constraints:

  • 3 <= equation.length <= 1000
  • equation has exactly one '='.
  • equation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable 'x'.

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public String solveEquation(String equation) {
    int[] equationFirst = parseEquation(equation.split("=")[0]);
    int[] equationSecond = parseEquation(equation.split("=")[1]);
    int constantPart = equationSecond[1] - equationFirst[1];
    int variablePart = equationFirst[0] - equationSecond[0];
    if (variablePart == 0) {
      return constantPart == 0 ? "Infinite solutions" : "No solution";
    }
    int sign = (variablePart  <  0 && constantPart < 0) || (variablePart > 0 && constantPart > 0) ? 1 : -1;
    if (Math.abs(constantPart) % Math.abs(variablePart) == 0) {
      constantPart = Math.abs(constantPart) / Math.abs(variablePart);
      variablePart = 1;
    } 
    return (variablePart > 1 ? variablePart : "") + "x=" + sign * constantPart;
  }
  
  private int[] parseEquation(String s) {
    int variablePart = 0;
    int constantPart = 0;
    int sign = 1;
    int n = s.length();
    for (int idx = 0; idx  <  n;) {
      if (s.charAt(idx) == 'x') {
        variablePart += sign;
        idx++;
        sign = 1;
      } else if (Character.isDigit(s.charAt(idx))) {
        int num = 0;
        while (idx  <  n && Character.isDigit(s.charAt(idx))) {
          num = num * 10 + Character.getNumericValue(s.charAt(idx++));
        }
        if (idx != n && s.charAt(idx) == 'x') {
          variablePart += sign * num;
          idx++;
        } else {
          constantPart += sign * num;
        }
        sign = 1;
      } else {
        sign = s.charAt(idx++) == '+' ? 1 : -1;
      }
    }
    return new int[]{variablePart, constantPart};
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
equation = "x+5-3+x=6+x-2"

Output

x
+
cmd
"x=2"

#2 Code Example with Javascript Programming

Code - Javascript Programming

 {
    num = 1
  } else {
    num = +tmp
  }
  return num
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
equation = "x+5-3+x=6+x-2"

Output

x
+
cmd
"x=2"

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def solveEquation(self, equation):
        def calc(eq):
            smX = smNum = 0
            add, num = True, ""
            for c in eq + "+":
                if c.isdigit():
                    num += c
                elif c == "x":
                    smX += int(num) if add and num else -int(num) if num else 1 if add else -1
                    num = ""
                else:
                    smNum += int(num) if add and num else -int(num) if num else 0
                    num, add = "", c == "+"
            return smX, smNum
        eq = equation.split("=")
        lX, lNum, rX, rNum = calc(eq[0]) + calc(eq[1])
        if lX == rX: 
            return "No solution" if lNum != rNum else "Infinite solutions"
        return "x=" + str((lNum - rNum) // (rX - lX))
Copy The Code & Try With Live Editor

Input

x
+
cmd
equation = "x=x"

Output

x
+
cmd
"Infinite solutions"
Advertisements

Demonstration


Previous
#639 Leetcode Decode Ways II Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#641 Leetcode Design Circular Deque Solution in C, C++, Java, JavaScript, Python, C# Leetcode