Showing
1 changed file
with
84 additions
and
0 deletions
13-romanToInt.js
0 → 100644
| 1 | +/** | ||
| 2 | + * @param {string} s | ||
| 3 | + * @return {number} | ||
| 4 | + */ | ||
| 5 | + | ||
| 6 | +/* | ||
| 7 | +var romanToInt = function (s) { | ||
| 8 | + const dict = { | ||
| 9 | + I: 1, | ||
| 10 | + V: 5, | ||
| 11 | + X: 10, | ||
| 12 | + L: 50, | ||
| 13 | + C: 100, | ||
| 14 | + D: 500, | ||
| 15 | + M: 1000 | ||
| 16 | + }; | ||
| 17 | + | ||
| 18 | + const sign = { | ||
| 19 | + I: {V: -1, X:-1}, | ||
| 20 | + X: {L: -1, C: -1}, | ||
| 21 | + C: {D: -1, M: -1} | ||
| 22 | + }; | ||
| 23 | + | ||
| 24 | + let num = 0; | ||
| 25 | + let last; | ||
| 26 | + | ||
| 27 | + s.split('').forEach(n => { | ||
| 28 | + let c = dict[n]; | ||
| 29 | + if (!c) { | ||
| 30 | + throw new Error('Wrong Roman Number'); | ||
| 31 | + } | ||
| 32 | + | ||
| 33 | + | ||
| 34 | + }) | ||
| 35 | +}; | ||
| 36 | +//*/ | ||
| 37 | + | ||
| 38 | +// 定义罗马数字和对应的整数值映射表 | ||
| 39 | +const romanToIntegerMap = new Map([ | ||
| 40 | + ['I', 1], | ||
| 41 | + ['V', 5], | ||
| 42 | + ['X', 10], | ||
| 43 | + ['L', 50], | ||
| 44 | + ['C', 100], | ||
| 45 | + ['D', 500], | ||
| 46 | + ['M', 1000] | ||
| 47 | +]); | ||
| 48 | +/** | ||
| 49 | + * 将罗马数字转换为整数。 | ||
| 50 | + * @param {string} romanNumeral - 罗马数字字符串。 | ||
| 51 | + * @returns {number} 转换后的整数值。 | ||
| 52 | + */ | ||
| 53 | +function romanToInt(romanNumeral) { | ||
| 54 | + const regex = /^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/; | ||
| 55 | + if (!regex.test(romanNumeral)) { | ||
| 56 | + throw new Error('Invalid Roman Numeral: ' + romanNumeral); | ||
| 57 | + } | ||
| 58 | + | ||
| 59 | + | ||
| 60 | + let total = 0; | ||
| 61 | + for (let i = 0; i < romanNumeral.length; i++) { | ||
| 62 | + const currentChar = romanNumeral[i]; | ||
| 63 | + const currentValue = romanToIntegerMap.get(currentChar); | ||
| 64 | + if (!currentValue) { | ||
| 65 | + throw new Error('Wrong Roman Number'); | ||
| 66 | + } | ||
| 67 | + | ||
| 68 | + // 如果下一个字符的值大于当前字符,那么需要从总和中减去当前值 | ||
| 69 | + if (i + 1 < romanNumeral.length && romanToIntegerMap.get(romanNumeral[i + 1]) > currentValue) { | ||
| 70 | + total -= currentValue; | ||
| 71 | + } else { | ||
| 72 | + total += currentValue; | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + | ||
| 76 | + console.info(i, '-', currentChar, ':', currentValue, '=', total); | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + return total; | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +// 示例使用: | ||
| 83 | +const romanInput = 'MCMXCIV'; | ||
| 84 | +console.info(`The integer value of ${romanInput} is ${romanToInt(romanInput)}.`); |
-
Please register or login to post a comment