forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
55 lines (55 loc) · 1.45 KB
/
Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
function solveEquation(equation: string): string {
const [left, right] = equation.split('=');
const createExpr = (s: string) => {
let x = 0;
let n = 0;
let i = 0;
let sym = 1;
let cur = 0;
let isX = false;
for (const c of s) {
if (c === '+' || c === '-') {
if (isX) {
if (i === 0 && cur === 0) {
cur = 1;
}
x += cur * sym;
} else {
n += cur * sym;
}
isX = false;
cur = 0;
i = 0;
if (c === '+') {
sym = 1;
} else {
sym = -1;
}
} else if (c === 'x') {
isX = true;
} else {
i++;
cur *= 10;
cur += Number(c);
}
}
if (isX) {
if (i === 0 && cur === 0) {
cur = 1;
}
x += cur * sym;
} else {
n += cur * sym;
}
return [x, n];
};
const lExpr = createExpr(left);
const rExpr = createExpr(right);
if (lExpr[0] === rExpr[0]) {
if (lExpr[1] !== rExpr[1]) {
return 'No solution';
}
return 'Infinite solutions';
}
return `x=${(lExpr[1] - rExpr[1]) / (rExpr[0] - lExpr[0])}`;
}