题目地址:Roman to Integer
题目简介:将特定的罗马字符串转换为整数,这里还有一些特定的规则。
罗马数字代码表:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
罗马数字除了以下六种情况均为直接相加即可:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900
Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
题目解析:理解罗马表,暴力。
C++版:
class Solution {
public:
int romanToInt(string s) {
int ans = 0;
s += " ";
for (int i = 0; i < s.length();i++)
{
if (s[i] == 'I' && s[i + 1] == 'V')
{
ans += 4;
i++;
}
else if (s[i] == 'I' && s[i + 1] == 'X')
{
ans += 9;
i++;
}
else if (s[i] == 'X' && s[i + 1] == 'L')
{
ans += 40;
i++;
}
else if (s[i] == 'X' && s[i + 1] == 'C')
{
ans += 90;
i++;
}
else if (s[i] == 'C' && s[i + 1] == 'D')
{
ans += 400;
i++;
}
else if (s[i] == 'C' && s[i + 1] == 'M')
{
ans += 900;
i++;
}
else if (s[i] == 'I')
ans += 1;
else if (s[i] == 'V')
ans += 5;
else if (s[i] == 'X')
ans += 10;
else if (s[i] == 'L')
ans += 50;
else if (s[i] == 'C')
ans += 100;
else if (s[i] == 'D')
ans += 500;
else if (s[i] == 'M')
ans += 1000;
}
return ans;
}
};
Python版本1:
class Solution:
def romanToInt(self, s: str) -> int:
ans = 0
s += " "
flag = 0
for i in range(len(s)):
if flag == 1:
flag = 0
elif (s[i] == 'I' and s[i + 1] == 'V'):
ans += 4
flag = 1
elif (s[i] == 'I' and s[i + 1] == 'X'):
ans += 9
flag = 1
elif (s[i] == 'X' and s[i + 1] == 'L'):
ans += 40
flag = 1
elif (s[i] == 'X' and s[i + 1] == 'C'):
ans += 90
flag = 1
elif (s[i] == 'C' and s[i + 1] == 'D'):
ans += 400
flag = 1
elif (s[i] == 'C' and s[i + 1] == 'M'):
ans += 900
flag = 1
elif (s[i] == 'I'):
ans += 1
elif (s[i] == 'V'):
ans += 5
elif (s[i] == 'X'):
ans += 10
elif (s[i] == 'L'):
ans += 50
elif (s[i] == 'C'):
ans += 100
elif (s[i] == 'D'):
ans += 500
elif (s[i] == 'M'):
ans += 1000;
return (ans)
Python版本2:利用Python的特性:
def romanToInt(self, s):
value, prevValue, result = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}, None, 0
for ch in s:
currValue = value[ch]
result += currValue
if prevValue and currValue > prevValue: result -= 2 * prevValue
prevValue = currValue
return result