代码如下:
#include<stdio.h>
#include<string.h>
int romanToInt(char* s) {
int romanNumbers[26];
romanNumbers['I'-'A'] = 1;
romanNumbers['V'-'A'] = 5;
romanNumbers['X'-'A'] = 10;
romanNumbers['L'-'A'] = 50;
romanNumbers['C'-'A'] = 100;
romanNumbers['D'-'A'] = 500;
romanNumbers['M'-'A'] = 1000;
int ans = 0, n = strlen(s);
for (int i = 0; i < n; i++) {
int number = romanNumbers[s[i]-'A'];
if (i < n - 1 && number < romanNumbers[s[i + 1]-'A']) {
ans -= number;
}
else {
ans += number;
}
}
return ans;
}
浅浅写个主函数debug一下:
int main() {
char S[] = "IV" ;
int ans = romanToInt(S);
printf("%d",ans);
}
结果如下: