-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0640-solve-the-equation.js
More file actions
71 lines (62 loc) · 2.21 KB
/
0640-solve-the-equation.js
File metadata and controls
71 lines (62 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Solve The Equation
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var solveEquation = function (equationInput) {
const equationParts = equationInput.split("=");
const leftPartStr = equationParts[0];
const rightPartStr = equationParts[1];
function processEquationPart(segmentToProcess) {
let xCountCurrent = 0;
let numberSumCurrent = 0;
let currentDigitsValue = 0;
let termSignFactor = 1;
for (
let iterationIdx = 0;
iterationIdx < segmentToProcess.length;
iterationIdx++
) {
const currentCharInSegment = segmentToProcess[iterationIdx];
if (currentCharInSegment === "x") {
const isImplicitOneCoefficient =
iterationIdx === 0 ||
segmentToProcess[iterationIdx - 1] === "+" ||
segmentToProcess[iterationIdx - 1] === "-";
xCountCurrent +=
termSignFactor *
(currentDigitsValue === 0 && isImplicitOneCoefficient
? 1
: currentDigitsValue);
currentDigitsValue = 0;
} else if (currentCharInSegment === "+" || currentCharInSegment === "-") {
numberSumCurrent += termSignFactor * currentDigitsValue;
termSignFactor = currentCharInSegment === "+" ? 1 : -1;
currentDigitsValue = 0;
} else {
currentDigitsValue =
currentDigitsValue * 10 + parseInt(currentCharInSegment, 10);
}
}
numberSumCurrent += termSignFactor * currentDigitsValue;
return { xAccumulator: xCountCurrent, numAccumulator: numberSumCurrent };
}
const leftResultObj = processEquationPart(leftPartStr);
const rightResultObj = processEquationPart(rightPartStr);
const lhsXTotal = leftResultObj.xAccumulator;
const lhsNumberTotal = leftResultObj.numAccumulator;
const rhsXTotal = rightResultObj.xAccumulator;
const rhsNumberTotal = rightResultObj.numAccumulator;
const combinedXCoeff = lhsXTotal - rhsXTotal;
const combinedNumberValue = rhsNumberTotal - lhsNumberTotal;
if (combinedXCoeff === 0) {
if (combinedNumberValue === 0) {
return "Infinite solutions";
} else {
return "No solution";
}
} else {
const solutionResult = combinedNumberValue / combinedXCoeff;
return `x=${solutionResult}`;
}
};