LintCode 1113. 解方程 JavaScript算法

描述

解一个给定的方程,以"x=#value"的格式返回x的值。方程仅仅包含’+‘运算、’-'运算、变量x和它的系数。

如果没有解,返回"No solution"。
如果有无穷解,返回"Infinite solutions"。
如果恰有一个解,此题确保该解为整数。

样例

- 样例 1:

输入: "x+5-3+x=6+x-2"
输出: "x=2"

- 样例 2:

输入: "x=x"
输出: "Infinite solutions"

- 样例 3:

输入: "2x=x"
输出: "x=0"

- 样例 4:

输入: "2x+3x-6x=x+2"
输出: "x=-1"

- 样例 5:

输入: "x=x+2"
输出: "No solution"

解析

var solveEquation = function(equation) {
    
    
  let xCount = 0; // x的数量
  let param = 0; // 剩余数值
  let arr = equation.split('=');
  let helper = function (equation, sym) {
    
    
    let tempParam = '';
    let symbol = '+'; // 当前符号
    let i = 0;
    equation += '+' // 等式最后加上一个'+'为了处理最后的剩余数值
    while(equation[i]) {
    
    
      let char = equation[i];
      if (char === 'x') {
    
    
        let temp = parseInt(tempParam  || 1)
        tempParam = '';
        symbol === sym ? xCount += temp : xCount -= temp
      } else if (char === "+" || char === "-") {
    
    
        let temp = parseInt(tempParam || 0)
        tempParam = '';
        symbol === sym ? param-=temp : param+=temp
        symbol = char
      } else {
    
    
        tempParam += char;
      }
      ++i;
    }
  }
  helper(arr[0], "+")
  helper(arr[1], "-")
  if (xCount === 0 && param === 0) return "Infinite solutions"
  if (xCount === 0) return "No solution"
  return 'x=' + (param/xCount)
};

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/SmallTeddy/article/details/108635832