37 lines
1.3 KiB
JavaScript
37 lines
1.3 KiB
JavaScript
/**
|
|
* 640.求解方程
|
|
* @param {string} equation 方程式
|
|
* @return {string} 解
|
|
* @see <a href="https://leetcode-cn.com/problems/solve-the-equation/">原题链接</a>
|
|
*/
|
|
const solveEquation = function (equation) {
|
|
let a = 0, b = 0, c = 0, sign = 1, left = 1, hasC = false;
|
|
for (let z of equation) {
|
|
switch (z) {
|
|
case 'x':
|
|
a += hasC ? sign * left * c : sign * left, c = 0, hasC = false;
|
|
break;
|
|
case '+':
|
|
b += sign * left * c, c = 0, sign = 1, hasC = false;
|
|
break;
|
|
case '-':
|
|
b += sign * left * c, c = 0, sign = -1, hasC = false;
|
|
break;
|
|
case '=':
|
|
b += sign * left * c, c = 0, sign = 1, left = -1, hasC = false;
|
|
break;
|
|
default:
|
|
c = c * 10 + (z - '0'), hasC = true;
|
|
break;
|
|
}
|
|
}
|
|
b += sign * left * c;
|
|
return a === 0 ? b === 0 ? "Infinite solutions" : "No solution" : "x=" + -b / a;
|
|
};
|
|
|
|
console.assert(solveEquation("x+5-3+x=6+x-2") === "x=2");
|
|
console.assert(solveEquation("x=x") === "Infinite solutions");
|
|
console.assert(solveEquation("2x=x") === "x=0");
|
|
console.assert(solveEquation("0x=0") === "Infinite solutions");
|
|
console.assert(solveEquation("0=0x") === "Infinite solutions");
|