Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/640.html
640. Solve the Equation (Medium)
Solve a given equation and return the value of x
in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x
and its coefficient.
If there is no solution for the equation, return "No solution".
If there are infinite solutions for the equation, return "Infinite solutions".
If there is exactly one solution for the equation, we ensure that the value of x
is an integer.
Example 1:
Input: "x+5-3+x=6+x-2" Output: "x=2"
Example 2:
Input: "x=x" Output: "Infinite solutions"
Example 3:
Input: "2x=x" Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2" Output: "x=-1"
Example 5:
Input: "x=x+2" Output: "No solution"
Related Topics:
Math
Similar Questions:
Solution 1.
-
class Solution { public String solveEquation(String equation) { equation = equation.replaceAll("-", "+-"); if (equation.charAt(0) == '+') equation = equation.substring(1); equation = equation.replace("=+", "="); int equalIndex = equation.indexOf('='); String leftSide = equation.substring(0, equalIndex); String rightSide = equation.substring(equalIndex + 1); String[] leftArray = leftSide.split("\\+"); String[] rightArray = rightSide.split("\\+"); int xTerm = 0, constantTerm = 0; for (String leftTerm : leftArray) { if (leftTerm.contains("x")) { if (leftTerm.equals("x")) xTerm++; else if (leftTerm.equals("-x")) xTerm--; else { String coefficientStr = leftTerm.substring(0, leftTerm.indexOf('x')); int coefficient = Integer.parseInt(coefficientStr); xTerm += coefficient; } } else constantTerm -= Integer.parseInt(leftTerm); } for (String rightTerm : rightArray) { if (rightTerm.contains("x")) { if (rightTerm.equals("x")) xTerm--; else if (rightTerm.equals("-x")) xTerm++; else { String coefficientStr = rightTerm.substring(0, rightTerm.indexOf('x')); int coefficient = Integer.parseInt(coefficientStr); xTerm -= coefficient; } } else constantTerm += Integer.parseInt(rightTerm); } if (xTerm != 0) { int solution = constantTerm / xTerm; return "x=" + solution; } else if (constantTerm == 0) return "Infinite solutions"; else return "No solution"; } } ############ class Solution { public String solveEquation(String equation) { String[] es = equation.split("="); int[] a = f(es[0]), b = f(es[1]); int x1 = a[0], y1 = a[1]; int x2 = b[0], y2 = b[1]; if (x1 == x2) { return y1 == y2 ? "Infinite solutions" : "No solution"; } return "x=" + (y2 - y1) / (x1 - x2); } private int[] f(String s) { int x = 0, y = 0; if (s.charAt(0) != '-') { s = "+" + s; } int i = 0, n = s.length(); while (i < n) { int sign = s.charAt(i) == '+' ? 1 : -1; ++i; int j = i; while (j < n && s.charAt(j) != '+' && s.charAt(j) != '-') { ++j; } String v = s.substring(i, j); if (s.charAt(j - 1) == 'x') { x += sign * (v.length() > 1 ? Integer.parseInt(v.substring(0, v.length() - 1)) : 1); } else { y += sign * Integer.parseInt(v); } i = j; } return new int[] {x, y}; } }
-
// OJ: https://leetcode.com/problems/solve-the-equation/ // Time: O(N) // Space: O(1) class Solution { private: int read(string &equation, int pos, bool &isNum, int &num) { if (equation[pos] == '=') ++pos; int sign = 1, N = equation.size(); if (equation[pos] == '+' || equation[pos] == '-') { if (equation[pos] == '-') sign = -1; ++pos; } if (pos < N && equation[pos] == 'x') { num = 1; } else { num = 0; while (pos < N && isdigit(equation[pos])) { num = num * 10 + equation[pos++] - '0'; } } isNum = true; if (pos < N && equation[pos] == 'x') { isNum = false; ++pos; } num *= sign; return pos; } public: string solveEquation(string equation) { int i = 0, N = equation.size(), space = equation.find_first_of("="); int coef = 0, val = 0; while (i < N) { bool isNum; int num; i = read(equation, i, isNum, num); int sign = i <= space ? 1 : -1; if (isNum) val -= sign * num; else coef += sign * num; } if (coef) return "x=" + to_string(val / coef); return val ? "No solution" : "Infinite solutions"; } };
-
class Solution: def solveEquation(self, equation: str) -> str: def f(s): x = y = 0 if s[0] != '-': s = '+' + s i, n = 0, len(s) while i < n: sign = 1 if s[i] == '+' else -1 i += 1 j = i while j < n and s[j] not in '+-': j += 1 v = s[i:j] if v[-1] == 'x': x += sign * (int(v[:-1]) if len(v) > 1 else 1) else: y += sign * int(v) i = j return x, y a, b = equation.split('=') x1, y1 = f(a) x2, y2 = f(b) if x1 == x2: return 'Infinite solutions' if y1 == y2 else 'No solution' return f'x={(y2 - y1) // (x1 - x2)}' ############ class Solution(object): def solveEquation(self, equation): """ :type equation: str :rtype: str """ left, right = equation.split("=") left = filter(lambda x: x, left.replace("+", "#P").replace("-", "#M").split("#")) right = filter(lambda x: x, right.replace("+", "#M").replace("-", "#P").split("#")) left[0] = "P" + left[0] if left[0][0] not in ["P", "M"] else left[0] right[0] = "M" + right[0] if right[0][0] not in ["P", "M"] else right[0] left += right a = b = 0 for param in left: param = param.replace("P", "+").replace("M", "-") if param[-1] == "x": k = 1 if len(param) > 2: k = int(param[1:-1]) if param[0] == "-": a -= k else: a += k else: b -= int(param) return "x={0}".format(str(b / a)) if a else "No solution" if b else "Infinite solutions"
-
func solveEquation(equation string) string { f := func(s string) []int { x, y := 0, 0 if s[0] != '-' { s = "+" + s } i, n := 0, len(s) for i < n { sign := 1 if s[i] == '-' { sign = -1 } i++ j := i for j < n && s[j] != '+' && s[j] != '-' { j++ } v := s[i:j] if s[j-1] == 'x' { a := 1 if len(v) > 1 { a, _ = strconv.Atoi(v[:len(v)-1]) } x += sign * a } else { a, _ := strconv.Atoi(v) y += sign * a } i = j } return []int{x, y} } es := strings.Split(equation, "=") a, b := f(es[0]), f(es[1]) x1, y1 := a[0], a[1] x2, y2 := b[0], b[1] if x1 == x2 { if y1 == y2 { return "Infinite solutions" } else { return "No solution" } } return fmt.Sprintf("x=%d", (y2-y1)/(x1-x2)) }
-
function solveEquation(equation: string): string { const [left, right] = equation.split('='); const createExpr = (s: string) => { let x = 0; let n = 0; let i = 0; let sym = 1; let cur = 0; let isX = false; for (const c of s) { if (c === '+' || c === '-') { if (isX) { if (i === 0 && cur === 0) { cur = 1; } x += cur * sym; } else { n += cur * sym; } isX = false; cur = 0; i = 0; if (c === '+') { sym = 1; } else { sym = -1; } } else if (c === 'x') { isX = true; } else { i++; cur *= 10; cur += Number(c); } } if (isX) { if (i === 0 && cur === 0) { cur = 1; } x += cur * sym; } else { n += cur * sym; } return [x, n]; }; const lExpr = createExpr(left); const rExpr = createExpr(right); if (lExpr[0] === rExpr[0]) { if (lExpr[1] !== rExpr[1]) { return 'No solution'; } return 'Infinite solutions'; } return `x=${(lExpr[1] - rExpr[1]) / (rExpr[0] - lExpr[0])}`; }