-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path13.罗马数字转整数.cpp
49 lines (44 loc) · 878 Bytes
/
13.罗马数字转整数.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// @before-stub-for-debug-begin
#include <vector>
#include <string>
#include <map>
#include "commoncppproblem13.h"
using namespace std;
// @before-stub-for-debug-end
/*
* @lc app=leetcode.cn id=13 lang=cpp
*
* [13] 罗马数字转整数
*/
// @lc code=start
class Solution
{
public:
int romanToInt(string s)
{
std::map<char, int> cnums{
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000},
};
int sums = 0;
int pre = 0;
int n = s.size();
for (int i = 0; i < n; ++i)
{
int val = cnums[s[i]];
sums += val;
if (pre < val)
{
sums -= 2 * pre;
}
pre = val;
}
return sums;
}
};
// @lc code=end