罗马数字与数字转换;(11月29日允许发题解)
思路:建立个映射表,将相应字母对应相应数字。每次走到一个字母,顺便判断下一个字母的情况,就ok了。
代码块:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int romanToInt(char* input,int len){
int romanToIntMap[26] = {
0,
0,
100,
500,
0,
0,
0,
0,
1,
0,
0,
50,
1000,
0,
0,
0,
0,
0,
0,
0,
0,
5,
0,
10,
0,
0
};
int result = 0;
int i = 0;
while (i<len) {
int currentVal = romanToIntMap[input[i] - 'A'];
int nextVal = romanToIntMap[input[i + 1] - 'A'];
if(currentVal==0&&nextVal==0)
return result;
if (nextVal && currentVal < nextVal&&len>=2) {
result += (nextVal - currentVal);
i += 2;
} else {
result += currentVal;
i++;
}
}
return result;
}
void intToRoman(int num) {
if (num <= 0 || num > 3999){
return;
}
const char *romanNumerals[] = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
const int values[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
int i = 12;
while (num > 0) {
int quotient = num / values[i];
num %= values[i];
for (int j = 0; j < quotient; j++){
printf("%s", romanNumerals[i]);
}
i--;
}
printf("\n");
}
int main(){
char rome[1000]={'0'};
scanf("%s",rome);
int si=strlen(rome);
char s[si];
for(int i=0;i<si;i++)
s[i]=rome[i];
const char* romanInput=s;
int c=atoi(s);
if(c)
intToRoman(c);
else
printf("%d\n",romanToInt(rome,si));
return 0;
}