一般思路,先判断能够出现的组合,然后判断每一位,计算他们的和
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
|
var romanToInt = function (s) { const map = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000, }; 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; };
|
高级思路,出现的组合都是两位,而且前一个数字比后一个数字小
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
|
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; };
|
reduce写法,逻辑通了其实代码很好写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
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); };
|