Leetcode 13. Roman to Integer

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Roman to Integer

Roman to Integer

2. Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int romanToInt(string s) {
map<char, int> values;
values['I'] = 1;
values['V'] = 5;
values['X'] = 10;
values['L'] = 50;
values['C'] = 100;
values['D'] = 500;
values['M'] = 1000;
int value = 0;
for(int i = 0; i < s.length() - 1; i++) {
if(values[s[i]] < values[s[i + 1]]) {
value -= values[s[i]];
}
else {
value += values[s[i]];
}
}
value += values[s[s.length() - 1]];
return value;
}
};

Reference

  1. https://leetcode.com/problems/roman-to-integer/description/
如果有收获,可以请我喝杯咖啡!