#include
#include
#define maxnumber 10
int value[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
char Roman[][3] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
//CCCLXIX=369
int Find(char key[]) {
int i;
for(i = 12; i>=0; i--) {
if(!strcmp(Roman[i],key)) return value[i];
}
return 0;
}
int Convert(char roman[]) {
int length = strlen(roman) - 1;
int i, val, sum = 0, find;
char tempRoman[4];
for(i = length; i>=0; ) {
find = 0;
if(i >= 1) {
tempRoman[0] = roman[i-1];
tempRoman[1] = roman[i];
tempRoman[2] = NULL;
val = Find(tempRoman);
if(val > 0) {
sum += val;
find = 1;
i -= 2;
}
}
if(find == 0) {
tempRoman[0] = roman[i];
tempRoman[1] = NULL;
sum += Find(tempRoman);
i--;
}
}
return sum;
}
int main() {
char roman[100];
// Insert a valid Roman number, all characters must be upper case
// Input range: up to 3999 ( MMMCMXCIX )
while(scanf("%s",roman) != EOF) {
printf("%d\n",Convert(roman));
}
return 0;
}
Basic Knowledge needed to understand this program :
1. U must know C ofcourse .
2. U must Also know how are decimal numbers represented using Roman letters .
How are they represented :
I : This represents 1 and Two I's represent 2 and three I's represent 3 . But this sequence cant be continued for representing four , five etc as it would take more I's . This Gives birth to
v : This represents 5 . placing an I in front of V means 4 . That is IV means 4 . Placing a smaller number in front of larger number indicates Subtraction and placing a smaller number after a larger number indicates Addition . Thus VI means 6[5+1] , VII means 7 , and VIII means 8 .
X : This represents 10 . Hope you found out how to represent 9 . It's IX ,as explainied before subtract I from X . The number of X's indicates the number of tens . Lets take XXIV . As there are 2 X's it indicates 20 and IV is 4. so its 24.
L : L means 50 . Based on what we've learnt so far it should be easy by now to predict how 40 will be represented . ya you are right . Its XL . 10(X) subtracted from 50(L) . And 60,70,80 are LX,LXX,LXXX .
C : C stands for Centum . It means 100 . So by previous explanations XC means 90. CCCLXIX means 369.
D : D stands for 500. Now you will be able to know how to represent 400 . Its simple CD.
M : M means 1000. This is mostly used to represent dates .
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.