Please check the below link to know about how to write roman numerals.
Write a C program to convert roman numeral to its hexadecimal equivalent.
#include <string.h>
#include <stdlib.h>
/* converts given value to its binary equivalent */
int romanToDeci(char ch) {
int retVal;
switch (ch) {
case 'I':
retVal = 1;
break;
case 'V':
retVal = 5;
break;
case 'X':
retVal = 10;
break;
case 'L':
retVal = 50;
break;
case 'C':
retVal = 100;
break;
case 'D':
retVal = 500;
break;
case 'M':
retVal = 1000;
break;
default:
printf("Wrong Input!!\n");
exit(0);
}
return retVal;
}
int decimalToHexa(int data) {
int rem[10], count = 0;
char hexa[] = {'A', 'B', 'C', 'D', 'E', 'F'};
/* convert decimal to hexadecimal value */
while (data > 0) {
rem[count++] = data % 16;
data = data / 16;
}
printf("Hexadecimal value : ");
while (count > 0) {
count--;
if (rem[count] > 9) {
printf("%c", hexa[rem[count] - 10]);
} else {
printf("%d", rem[count]);
}
}
printf("\n");
return 0;
}
int main() {
char roman[100];
int value, i, j, len;
/* get the roman numeral from the user */
printf("Enter your Roman Numeral:");
fgets(roman, 100, stdin);
roman[strlen(roman) - 1] = '\0';
len = strlen(roman);
/* roman to decimal conversion */
value = romanToDeci(roman[len - 1]);
for (i = len - 1; i > 0; i--) {
/*
* For roman numeral like IV, XL etc, the previous
* digit will be lesser than the current digit. So,
* we can find their decimal equivalent as follows.
* IV => V - I => 5 - 1 => 4
* XL => L - X => 50 - 10 => 40
*/
if (romanToDeci(roman[i]) > romanToDeci(roman[i - 1])) {
value = value - romanToDeci(roman[i - 1]);
} else {
value = value + romanToDeci(roman[i - 1]);
}
}
decimalToHexa(value);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your Roman Numeral:XCIX
Hexadecimal value : 63
Enter your Roman Numeral:XCIX
Hexadecimal value : 63
No comments:
Post a Comment