640. 求解方程 - 力扣(LeetCode)
- factor表示变量的系数,val表示常量值
- 使用系数sign1表示默认系数,解析到等号时,说明解析到等式右边的项,令sign1 = -1
- 使用sign2表示项的符号,初识时sign2 = sign1 。解析到‘+’,‘-’,要么相应的更改sign2,使用number记录数字,valid表示number是否有效
- 如果解析到变量,那么相应的更改factor
- 如果解析到的是常量项,那么相应的更改val
- 如果factor=0,说明变量x对方程无影响,然后判断val=0 是否成立,成立则说明方程有无数解,返回“Infinite solutions”否则返回“No solution”
- 其他情况直接返回对应的整数解 x= - val / factor
var solveEquation = function(equation) {
let factor = 0, val = 0;
let index = 0, n = equation.length, sign1 = 1;
while (index < n) {
if (equation[index] === '=') {
sign1 = -1;
index++;
continue;
}
let sign2 = sign1, number = 0;
let valid = false;
if (equation[index] === '-' || equation[index] === '+') {
sign2 = (equation[index] === '-') ? -sign1 : sign1;
index++;
}
while (index < n && isDigit(equation[index])) {
number = number * 10 + (equation[index].charCodeAt() - '0'.charCodeAt());
index++;
valid = true;
}
if (index < n && equation[index] === 'x') {
factor += valid ? sign2 * number : sign2;
index++;
} else {
val += sign2 * number;
}
}
if (factor === 0) {
return val === 0 ? "Infinite solutions" : "No solution";
}
return "x=" + (-val / factor);
};
const isDigit = (ch) => {
return parseFloat(ch).toString() === "NaN" ? false : true;
}
执行结果:通过
执行用时:56 ms, 在所有 JavaScript 提交中击败了88.46%的用户
内存消耗:41.1 MB, 在所有 JavaScript 提交中击败了65.38%的用户
通过测试用例:59 / 59
const CHARS = '-+=x'
function solveEquation(equation){
equation += '='
let sign = 1,cur = 0,num = 0, k = 0, left = true, hasVal = false;
for(let i=0i<equation.length;i++){
const c = equation.charAt(i);
if(CHARS.includes(c)){
if(c == 'x'){
if(!hasVal && cur == 0 ){
cur =1;
}
k+= left? sign * cur : -sign*cur;
}else{
num -= left? sign*cur:-sign*cur;
}
cur = 0;
hasVal = false;
}
switch(c){
case '-':
sign = -1;
break
case '+':
sign = 1;
break;
case '=':
sign = 1;
left = false;
break;
case 'x':
break;
default:
cur = cur * 10 +equation.charCodeAt(i) - '0'.charCodeAt(0)
hasVal = true;
break;
}
if(k == 0){
return num!=0? "No solution" : "Infinite solutions";
}
return num%k == 0? 'x='+Math.floor(num/k):"No solution"
}
}
参考链接
640. 求解方程 - 力扣(LeetCode)
求解方程 - 求解方程 - 力扣(LeetCode)
[[Python/Java/TypeScript/Go] 模拟 - 求解方程 - 力扣(LeetCode)](
|