|
| 1 | +/** |
| 2 | + * 640. Solve the Equation |
| 3 | + * https://leetcode.com/problems/solve-the-equation/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Solve a given equation and return the value of 'x' in the form of a string "x=#value". |
| 7 | + * The equation contains only '+', '-' operation, the variable 'x' and its coefficient. |
| 8 | + * You should return "No solution" if there is no solution for the equation, or "Infinite |
| 9 | + * solutions" if there are infinite solutions for the equation. |
| 10 | + * |
| 11 | + * If there is exactly one solution for the equation, we ensure that the value of 'x' is |
| 12 | + * an integer. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {string} equation |
| 17 | + * @return {string} |
| 18 | + */ |
| 19 | +var solveEquation = function(equation) { |
| 20 | + const [left, right] = equation.split('='); |
| 21 | + const leftSide = parseSide(left); |
| 22 | + const rightSide = parseSide(right); |
| 23 | + const totalX = leftSide.xCount - rightSide.xCount; |
| 24 | + const totalNum = rightSide.numSum - leftSide.numSum; |
| 25 | + |
| 26 | + if (totalX === 0 && totalNum === 0) return 'Infinite solutions'; |
| 27 | + if (totalX === 0) return 'No solution'; |
| 28 | + |
| 29 | + return `x=${totalNum / totalX}`; |
| 30 | + |
| 31 | + function parseSide(side) { |
| 32 | + let xCount = 0; |
| 33 | + let numSum = 0; |
| 34 | + let currentNum = 0; |
| 35 | + let sign = 1; |
| 36 | + |
| 37 | + for (let i = 0; i < side.length; i++) { |
| 38 | + const char = side[i]; |
| 39 | + if (char === 'x') { |
| 40 | + const v = i === 0 || side[i-1] === '+' || side[i-1] === '-'; |
| 41 | + xCount += sign * (currentNum === 0 && (v) ? 1 : currentNum); |
| 42 | + currentNum = 0; |
| 43 | + } else if (char === '+' || char === '-') { |
| 44 | + numSum += sign * currentNum; |
| 45 | + sign = char === '+' ? 1 : -1; |
| 46 | + currentNum = 0; |
| 47 | + } else { |
| 48 | + currentNum = currentNum * 10 + parseInt(char); |
| 49 | + } |
| 50 | + } |
| 51 | + numSum += sign * currentNum; |
| 52 | + |
| 53 | + return { xCount, numSum }; |
| 54 | + } |
| 55 | +}; |
0 commit comments