Skip to content

Latest commit

 

History

History
62 lines (54 loc) · 1.33 KB

640.求解方程.md

File metadata and controls

62 lines (54 loc) · 1.33 KB

640.求解方程

/*
 * @lc app=leetcode.cn id=640 lang=typescript
 *
 * [640] 求解方程
 */

// @lc code=start
function solveEquation(equation: string): string {}
// @lc code=end

解法 1: 合并同类项

function solveEquation(equation: string): string {
  const [left, right] = equation.split('=')
  const h = (s: string) => {
    let x = 0,
      y = 0,
      pre = ''
    const calc = () => {
      if (pre === 'x' || pre === '+x') x++
      else if (pre === '-x') x--
      else if (pre[pre.length - 1] === 'x') x += Number(pre.slice(0, pre.length - 1))
      else y += Number(pre)
      pre = ''
    }
    for (let i = 0; i < s.length; i++) {
      if (s[i] === '+' || s[i] === '-') {
        calc()
      }
      pre += s[i]
    }
    calc()
    return [x, y]
  }
  const [lx, ly] = h(left),
    [rx, ry] = h(right)

  const a = ry - ly,
    b = lx - rx

  if (a === 0 && b === 0) return 'Infinite solutions'
  if (b === 0 || a % b !== 0) return 'No solution'
  return `x=${a / b}`
}

Case

test.each([
  { input: { equation: 'x+5-3+x=6+x-2' }, output: 'x=2' },
  { input: { equation: 'x=x' }, output: 'Infinite solutions' },
  { input: { equation: '2x=x' }, output: 'x=0' },
])('input: equation = $input.equation', ({ input: { equation }, output }) => {
  expect(solveEquation(equation)).toEqual(output)
})