Please check the below link to know about how to write roman numerals.
Write a C program to convert roman numeral to its binary equivalent.
#include <string.h>
#include <stdlib.h>
/* converts given value to its binary equivalent */
int romToDeci(char ch) {
int ret;
switch (ch) {
case 'I':
ret = 1;
break;
case 'V':
ret = 5;
break;
case 'X':
ret = 10;
break;
case 'L':
ret = 50;
break;
case 'C':
ret = 100;
break;
case 'D':
ret = 500;
break;
case 'M':
ret = 1000;
break;
default:
printf("Wrong Input!!\n");
exit(0);
}
return ret;
}
int decimalToBinary(int data) {
int res = 0, i = 1, mod;
/* convert decimal to binary format */
while (data > 0) {
mod = data % 2;
res = res + (i * mod);
data = data / 2;
i = i * 10;
}
return res;
}
int main() {
char data[100];
int value, i, j, len;
/* get the roman numeral from the user */
printf("Enter your Roman Numeral:");
fgets(data, 100, stdin);
data[strlen(data) - 1] = '\0';
len = strlen(data);
/* roman to decimal conversion */
value = romToDeci(data[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 (romToDeci(data[i]) > romToDeci(data[i - 1])) {
value = value - romToDeci(data[i - 1]);
} else {
value = value + romToDeci(data[i - 1]);
}
}
printf("Binary Value: %d\n", decimalToBinary(value));
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your Roman Numeral:XCIX
Binary Value: 1100011
Enter your Roman Numeral:XCIX
Binary Value: 1100011
No comments:
Post a Comment