Skip to content

Commit 69a123b

Browse files
committed
Add solution #640
1 parent 4091bb6 commit 69a123b

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,7 @@
483483
637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy|
484484
638|[Shopping Offers](./0638-shopping-offers.js)|Medium|
485485
639|[Decode Ways II](./0639-decode-ways-ii.js)|Hard|
486+
640|[Solve the Equation](./0640-solve-the-equation.js)|Medium|
486487
641|[Design Circular Deque](./0641-design-circular-deque.js)|Medium|
487488
643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy|
488489
645|[Set Mismatch](./0645-set-mismatch.js)|Medium|

solutions/0640-solve-the-equation.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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

Comments
 (0)