Solve the Equation

Problem Id: 640 Difficulty: Medium


Intuition

Solution


class Solution:
    def solveEquation(self, equation: str) -> str:
        left, right = equation.split('=')
        a, b = self.combine(left)
        c, d = self.combine(right)
        kx = a - c
        kc = b - d
        if kx == 0 and kc != 0:
            return "No solution"
        elif kx == 0 and kc == 0:
            return "Infinite solutions"
        return "x=%d" % (-kc / kx)

    def combine(self, expr):
        pos = True
        prev = ""
        kx = 0
        kc = 0
        for c in expr + "\0":
            if c not in string.digits:
                if c == 'x':
                    if not prev:
                        prev = 1
                    kx += int(prev) if pos else (-1 * int(prev))
                elif prev:
                    kc += int(prev) if pos else (-1 * int(prev))
                pos = True
                prev = ''
                if c == '+':
                    pos = True
                elif c == '-':
                    pos = False
            else:
                prev += c
        return kx, kc