Description
character value
the I. 1
V. 5
X-10
L 50
C 100
D 500
M 1000
I may be on the left V (5) and X (10), and to represent 4 and 9.
X L can be placed on the left (50) and C (100), and 40 and 90 are represented.
C may be placed on D (500) and M (1000) to the left, to 400 and 900 represent.
Given a Roman numeral, to convert it to an integer. To ensure that the input is in the range of 1 to 3999
example
Thinking
- switch faster than some more dict
- IV IX XL XC CD CM centralized exceptional circumstances, if the current is less than the Roman numerals behind the Roman numerals, on subtracting the current Roman numerals, Roman numerals or plus the current
answer - python (no switch)
class Solution:
def romanToInt(self, s: str) -> int:
d={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
num=0
for i in range(len(s)):
if i+1<=len(s)-1 and d[s[i+1]]>d[s[i]]:
num -= d[s[i]]
else:
num += d[s[i]]
return num
- c++
* 用字典
class Solution {
public:
int romanToInt(string s) {
unordered_map<char,int> dict={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
int num=0;
for (int i=0; i<s.size(); i++)
{
if (i+1<=s.size()-1 && dict[s[i+1]]>dict[s[i]])
num -= dict[s[i]];
else
num += dict[s[i]];
}
return num;
}
};
* 用switch
int romanToInt(string s) {
int num=0;
int now=0;
int pre=0;
for (int i=0; i<s.size(); i++)
{
switch(s[i]) {
case 'I': now = 1; break;
case 'V': now = 5; break;
case 'X': now = 10; break;
case 'L': now = 50; break;
case 'C': now = 100; break;
case 'D': now = 500; break;
case 'M': now = 1000; break;
}
if (pre<now) num-=pre*2;
num+=now;
pre=now;
}
return num;
}
};