Skip to content

Instantly share code, notes, and snippets.

@ufo22940268
Created May 23, 2021 01:19
Show Gist options
  • Save ufo22940268/f1f953f9f9d27687f1b0812c0f37a826 to your computer and use it in GitHub Desktop.
Save ufo22940268/f1f953f9f9d27687f1b0812c0f37a826 to your computer and use it in GitHub Desktop.
//Solve a given equation and return the value of 'x' in the form of a string "x=
//#value". The equation contains only '+', '-' operation, the variable 'x' and its
// coefficient. You should return "No solution" if there is no solution for the eq
//uation, or "Infinite solutions" if there are infinite solutions for the equation
//.
//
// If there is exactly one solution for the equation, we ensure that the value o
//f 'x' is an integer.
//
//
// Example 1:
// Input: equation = "x+5-3+x=6+x-2"
//Output: "x=2"
// Example 2:
// Input: equation = "x=x"
//Output: "Infinite solutions"
// Example 3:
// Input: equation = "2x=x"
//Output: "x=0"
// Example 4:
// Input: equation = "2x+3x-6x=x+2"
//Output: "x=-1"
// Example 5:
// Input: equation = "x=x+2"
//Output: "No solution"
//
//
// Constraints:
//
//
// 3 <= equation.length <= 1000
// equation has exactly one '='.
// equation consists of integers with an absolute value in the range [0, 100] wi
//thout any leading zeros, and the variable 'x'.
//
// Related Topics 数学
// 👍 71 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* @param {string} equation
* @return {string}
*/
var solveEquation = function (equation) {
const [left, right] = equation.split('=')
let xp = 0;
let np = 0;
function process(s, xop, nop) {
if (!['+', '-'].includes(s[0])) s = '+' + s;
while (s.length) {
let m = s.match(/^([+-])(\d*)?([x]?)/)
if (m && m.length) {
let p = Number.parseInt(m[1] + '1');
let n = m[2] == undefined ? 1 : m[2];
if (m[3] == 'x') {
p = xop * p;
xp = xp + n * p;
} else {
p = nop * p;
np = np + n * p;
}
s = s.slice(m[0].length);
}
}
}
process(left, 1, -1);
process(right, -1, 1);
if (xp == 0 && np == 0) {
return 'Infinite solutions';
} else if (xp == 0) {
return 'No solution';
} else {
return 'x=' + np / xp;
}
};
//leetcode submit region end(Prohibit modification and deletion)
// const r = solveEquation('x+5-3+x=6+x-2')
const r = solveEquation('-x=1');
console.log(`r: ` + JSON.stringify(r, null, 4) + '\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment