Bookmark and Share

free counters
Back to Problem list
Problem 32: Write a program in C which takes Roman numbers as input and convert it equivalent 
Decimal number

Solution:

#include<stdio.h>
#include<string.h>

#define maxn 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"};

//MCDXLVIII = 1448

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
	// lx is an invalid input where LX is a valid input
	// Press Clt+z or Clt+c to exit from the program
    // Input range: up to 3999 ( MMMCMXCIX )

	while(scanf("%s",roman) != EOF)  {
		printf("%d\n",Convert(roman));
	}
    return 0;
}

Back to Problem list