Roman to Integer (Easy)

Description

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Analysis

罗马数字转换成数字。因为肯定是非递增的,突然递增的情况下就是相减

My 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
25
26
27
28
29
//C++
class Solution {
int checknum(char c){
if(c=='I') return 1;
if(c=='V') return 5;
if(c=='X') return 10;
if(c=='L') return 50;
if(c=='C') return 100;
if(c=='D') return 500;
if(c=='M') return 1000;
return 0;
}
public:
int romanToInt(string s) {
int ans = 0,pre;
for(int i=(int)s.length()-1;i>=0;i--){
if(ans==0){
pre = checknum(s[i]);
ans+=pre;
}
else{
int now = checknum(s[i]);
ans+=now*(now>=pre?1:-1);
pre = now;
}
}
return ans;
}
};