[13] Roman to Integer
© Jarvus Chen / www.jarvus.net
Description
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Required knowledge
Roman numerals conversion table
- I = 1
- V = 5
- X = 10
- L = 50
- C = 100
- D = 500
- M = 1000
Number | Roman | Number | Roman | Number | Roman | Number | Roman |
---|---|---|---|---|---|---|---|
1 | I | 10 | X | 100 | C | 1000 | M |
2 | II | 20 | XX | 200 | CC | 2000 | MM |
3 | III | 30 | XXX | 300 | CCC | 3000 | MMM |
4 | IV | 40 | XL | 400 | CD | ||
5 | V | 50 | L | 500 | D | ||
6 | VI | 60 | LX | 600 | DC | ||
7 | VII | 70 | LXX | 700 | DCC | ||
8 | VIII | 80 | LXXX | 800 | DCCC | ||
9 | IX | 90 | XC | 900 | CM |
My solution ( Beat 96.96% )
add
is the move distance for the next position in string.
int romanToInt(char* s) {
char *data = "IVXLCDM00";
int value[9]= {1,5,10,50,100,500,1000,0,0};
int ans = 0;
int i = 0;
int add = 1;
int size = strlen(s);
while ( i < size ){
add = 1;
for ( int j = 0 ; j < 7 ; j++){
if ( s[i] == data[j] ){
if ( i != size ){
if ( s[i+1] == data[j+1] ){
ans = ans + value[j+1] - value[j];
add = add + 1;
}else if( s[i+1] == data[j+2] ){
ans = ans + value[j+2] - value[j];
add = add + 1;
}else{
ans = ans + value[j];
}
}
}
}
i = i + add;
}
return ans;
}
Others solution
https://discuss.leetcode.com/topic/71045/a-c-solution-easy-to-understand
Use weight
as the index for all ACSII.
int romanToInt(char* s) {
int weight[256] = {0}; // store weights of I,V,X,L,C,D,M
weight['I'] = 1;
weight['V'] = 5;
weight['X'] = 10;
weight['L'] = 50;
weight['C'] = 100;
weight['D'] = 500;
weight['M'] = 1000;
int weight_pre = 0;
int i = strlen(s) - 1;
int num = 0;
while(i >= 0) {
if(weight[s[i]] >= weight_pre)
num += weight[s[i]];
else
num -= weight[s[i]];
weight_pre = weight[s[i--]];
}
return num;
}