Skip to content

Commit ae3dedb

Browse files
authored
Create 640-solve-the-equation.js
1 parent e94b592 commit ae3dedb

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

640-solve-the-equation.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* @param {string} equation
3+
* @return {string}
4+
*/
5+
function solveEquation (equation) {
6+
const strArr = equation.split('=')
7+
const leftHash = build(strArr[0])
8+
const rightHash = build(strArr[1])
9+
const xnum = leftHash.x - rightHash.x
10+
const num = rightHash.num - leftHash.num
11+
if(xnum === 0 && num !== 0) {
12+
return "No solution"
13+
} else if(xnum === 0) {
14+
return "Infinite solutions"
15+
} else {
16+
return `x=${num / xnum}`
17+
}
18+
};
19+
20+
function build(str) {
21+
let cur = ''
22+
const map = {
23+
num:0,
24+
x:0
25+
}
26+
for(let i = 0; i < str.length; i++) {
27+
if(str[i] === '-' || str[i] === '+') {
28+
chkCur(cur, map)
29+
cur = str[i]
30+
} else {
31+
cur += str[i]
32+
}
33+
}
34+
if(cur !== '') {
35+
chkCur(cur, map)
36+
}
37+
return map
38+
}
39+
function chkCur(cur, map) {
40+
let xIdx = cur.indexOf('x')
41+
if(xIdx === -1) {
42+
map.num += +cur
43+
} else {
44+
map.x += chkX(cur, xIdx)
45+
}
46+
}
47+
function chkX(str, xIdx) {
48+
let tmp = str.slice(0,xIdx)
49+
let num = 0
50+
if(tmp === '-') {
51+
num = -1
52+
} else if(tmp === '' || tmp === '+') {
53+
num = 1
54+
} else {
55+
num = +tmp
56+
}
57+
return num
58+
}

0 commit comments

Comments
 (0)