forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
romanToInteger.cpp
68 lines (64 loc) · 1.56 KB
/
romanToInteger.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Source : https://oj.leetcode.com/problems/roman-to-integer/
// Author : Hao Chen
// Date : 2014-07-17
/**********************************************************************************
*
* Given a roman numeral, convert it to an integer.
*
* Input is guaranteed to be within the range from 1 to 3999.
*
**********************************************************************************/
#include <iostream>
#include <string>
using namespace std;
int romanCharToInt(char ch){
int d = 0;
switch(ch){
case 'I':
d = 1;
break;
case 'V':
d = 5;
break;
case 'X':
d = 10;
break;
case 'L':
d = 50;
break;
case 'C':
d = 100;
break;
case 'D':
d = 500;
break;
case 'M':
d = 1000;
break;
}
return d;
}
int romanToInt(string s) {
if (s.size()<=0) return 0;
int result = romanCharToInt(s[0]);
for (int i=1; i<s.size(); i++){
int prev = romanCharToInt(s[i-1]);
int curr = romanCharToInt(s[i]);
//if left<right such as : IV(4), XL(40), IX(9) ...
if (prev < curr) {
result = result - prev + (curr-prev);
}else{
result += curr;
}
}
return result;
}
int main(int argc, char**argv)
{
string s("XL");
if (argc>1){
s = argv[1];
}
cout << s << " : " << romanToInt(s) << endl;
return 0;
}