leetcode-13 罗马数字转整数

一般思路,先判断能够出现的组合,然后判断每一位,计算他们的和

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
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function (s) {
const map = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
// I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。 IV IX
// X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 XL XC
// C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。 CD CM
let str = s;
let result = 0;
while (str) {
while (str.length > 0) {
if (str.startsWith("IV")) {
result += 4;
str = str.slice(2);
continue;
} else if (str.startsWith("IX")) {
result += 9;
str = str.slice(2);
continue;
} else if (str.startsWith("XL")) {
result += 40;
str = str.slice(2);
continue;
} else if (str.startsWith("XC")) {
result += 90;
str = str.slice(2);
continue;
} else if (str.startsWith("CD")) {
result += 400;
str = str.slice(2);
continue;
} else if (str.startsWith("CM")) {
result += 900;
str = str.slice(2);
continue;
}
break;
}
if (!str.length) break;
result += map[str[0]];
str = str.slice(1);
}
return result;
};
// console.log(romanToInt("MCMXCIV"));

高级思路,出现的组合都是两位,而且前一个数字比后一个数字小

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
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function (s) {
const map = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
let result = 0;
for (let i = 0; i < s.length; i++) {
const cur = map[s[i]],
next = map[s[i + 1]] || 0;
if (cur < next) {
result -= cur;
} else {
result += cur;
}
}
return result;
};
// console.log(romanToInt("MCMXCIV"));

reduce写法,逻辑通了其实代码很好写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function (s) {
const map = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
let result = 0;
return [...s].reduce((total, idx, i, arr) => {
const cur = map[idx];
const next = map[arr[i + 1]] || 0;
return cur < next ? total - cur : total + cur;
}, 0);
};
// console.log(romanToInt("MCMXCIV"));

本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。