# Code language: Python classSolution: defsolveEquation(self, equation: str) -> str: # 化为 kx = b 的形式 left, k, b, neg = 1, 0, 0, 1 cur = "" for e in equation: if e == 'x': num = int(cur) if cur else1 k += left * neg * num cur = "" elif e in"+-=": if cur: num = int(cur) b += -left * neg * num if e == '=': left = -1 neg = 1 elif e == '-': neg = -1 else: neg = 1 cur = "" else: cur += e if cur: b += -left * neg * int(cur) if k == 0: return"Infinite solutions"if b == 0else"No solution" returnf"x={b // k}"
// Code language: Java classSolution { public String solveEquation(String equation) { intleft=1, k = 0, b = 0, neg = 1; Stringcur=""; for (inti=0, n = equation.length(); i < n; ++i) { chare= equation.charAt(i); if (e == 'x') { intnum= cur.isEmpty() ? 1 : Integer.parseInt(cur); k += left * neg * num; cur = ""; } elseif (e == '+' || e == '-' || e == '=') { if (!cur.isEmpty()) { intnum= Integer.parseInt(cur); b -= left * neg * num; } neg = 1; if (e == '=') left = -1; elseif (e == '-') neg = -1; cur = ""; } else cur += e; } if (!cur.isEmpty()) b -= left * neg * Integer.parseInt(cur); if (k == 0) return b == 0 ? "Infinite solutions" : "No solution"; return"x=" + String.valueOf(b / k); } }
// Code language: C++ classSolution { public: string solveEquation(string equation){ int left = 1, k = 0, b = 0, neg = 1; string cur = ""; for (char e: equation) { if (e == 'x') { int num = cur.empty() ? 1 : atoi(cur.c_str()); k += left * neg * num; cur = ""; } elseif (e == '+' || e == '-' || e == '=') { if (!cur.empty()) { int num = atoi(cur.c_str()); b -= left * neg * num; } neg = 1; if (e == '=') left = -1; elseif (e == '-') neg = -1; cur = ""; } else cur += e; } if (!cur.empty()) b -= left * neg * atoi(cur.c_str()); if (k == 0) return b == 0 ? "Infinite solutions" : "No solution"; return"x=" + to_string(b / k); } };