跳到主要内容

13.罗马数字转整数

链接:13.罗马数字转整数
难度:Easy
标签:哈希表、数学、字符串
简介:给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。

题解 1 - typescript

  • 编辑时间:2020-06-02
  • 执行用时:192ms
  • 内存消耗:42MB
  • 编程语言:typescript
  • 解法介绍:特殊值进行特殊情况处理,为防止超标,在最后一位增加 0。
function romanToInt(s: string): number {
const len = s.length;
const romans: {
[index: string]: number;
} = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
N: 0,
};
s += 'N';
let num = 0;
let tempNum = 0;
let preRoman = '';
for (let i = 0; i < len; i++) {
const c = s[i];
switch (c) {
case 'C': {
if (preRoman === 'X') {
num += romans[(preRoman = c)] - tempNum;
tempNum = 0;
} else {
const n = romans[(preRoman = c)];
tempNum += n;
while (s[i + 1] === 'C') {
tempNum += n;
i++;
}
if (s[i + 1] !== 'D' && s[i + 1] !== 'M') {
num += tempNum;
tempNum = 0;
}
}
break;
}
case 'X': {
if (preRoman === 'I') {
num += romans[(preRoman = c)] - tempNum;
tempNum = 0;
} else {
const n = romans[(preRoman = c)];
tempNum += n;
while (s[i + 1] === 'X') {
tempNum += n;
i++;
}
if (s[i + 1] !== 'L' && s[i + 1] !== 'C') {
num += tempNum;
tempNum = 0;
}
}
break;
}
case 'I': {
const n = romans[(preRoman = c)];
tempNum += n;
while (s[i + 1] === 'I') {
tempNum += n;
i++;
}
if (s[i + 1] !== 'V' && s[i + 1] !== 'X') {
num += tempNum;
tempNum = 0;
}
break;
}
default: {
num += romans[(preRoman = c)] - tempNum;
tempNum = 0;
}
}
}
return num;
}

题解 2 - typescript

  • 编辑时间:2021-05-15
  • 执行用时:160ms
  • 内存消耗:46.2MB
  • 编程语言:typescript
  • 解法介绍:遍历。
function romanToInt(s: string): number {
let ans = 0;
const scoreCache: Record<string, number> = {
M: 1000,
D: 500,
L: 50,
V: 5,
};
const specCache: Record<string, [string, string, number]> = {
C: ['D', 'M', 100],
X: ['L', 'C', 10],
I: ['V', 'X', 1],
};
for (let i = 0, l = s.length; i < l; i++) {
const c = s[i];
const data = specCache[c];
if (data) {
const [c1, c2, num] = data;
if (s[i + 1] === c1) {
i++;
ans += 4 * num;
} else if (s[i + 1] === c2) {
i++;
ans += 9 * num;
} else {
ans += 1 * num;
}
} else ans += scoreCache[c];
}
return ans;
}

题解 3 - cpp

  • 编辑时间:2021-12-20
  • 执行用时:4ms
  • 内存消耗:5.9MB
  • 编程语言:cpp
  • 解法介绍:遍历模拟。
class Solution {
public:
int romanToInt(string s) {
int ans = 0;
for (int i = 0; i < s.size(); i++) {
char ch = s[i];
if (ch == 'M')
ans += 1000;
else if (ch == 'D')
ans += 500;
else if (ch == 'C') {
if (s[i + 1] == 'M') {
ans += 900;
i++;
} else if (s[i + 1] == 'D') {
ans += 400;
i++;
} else
ans += 100;
} else if (ch == 'L')
ans += 50;
else if (ch == 'X') {
if (s[i + 1] == 'C') {
ans += 90;
i++;
} else if (s[i + 1] == 'L') {
ans += 40;
i++;
} else
ans += 10;
} else if (ch == 'V')
ans += 5;
else if (ch == 'I') {
if (s[i + 1] == 'X') {
ans += 9;
i++;
} else if (s[i + 1] == 'V') {
ans += 4;
i++;
} else
ans += 1;
}
}
return ans;
}
};