给定一个罗马数字,将其转换成整数。伪代码是Function romanToInt(s) If s == M return 1000 If s == D return 500…
- User
给定一个罗马数字,将其转换成整数。伪代码是Function romanToInt(s) If s == M return 1000 If s == D return 500 ... If s.substr(2) == CM return 900+romanToInt(s+2) If s.substr(2) == CD return 400+romanToInt(s+2) ... If s[0] == M return 1000+romanToInt(s+1) If s[0] == D return 500+romanToInt(s+1) ... endfunc写出c语言代码
- Assistant
int romanToInt(char* s) { if (strcmp(s, "M") == 0) return 1000; if (strcmp(s, "D") == 0) return 500; ... if (strncmp(s, "CM", 2) == 0) return 900 + romanToInt(s + 2); if (strncmp(s, "CD", 2) == 0) return 400 + romanToInt(s + 2); ... if (s[0] == 'M') return 1000 + romanToInt(s + 1); if (s[0] == 'D') return 500 + romanToInt(s + 1); ... return 0; }
- User
把省略号展开详细写一下
- Assistant
int romanToInt(char* s) { if (strcmp(s, "M") == 0) return 1000; if (strcmp(s, "D") == 0) return 500; if (strcmp(s, "C") == 0) return 100; if (strcmp(s, "L") == 0) return 50; if (strcmp(s, "X") == 0) return 10; if (strcmp(s, "V") == 0) return 5; if (strcmp(s, "I") == 0) return 1;
codeif (strncmp(s, "CM", 2) == 0) return 900 + romanToInt(s + 2); if (strncmp(s, "CD", 2) == 0) return 400 + romanToInt(s + 2); if (strncmp(s, "XC", 2) == 0) return 90 + romanToInt(s + 2); if (strncmp(s, "XL", 2) == 0) return 40 + romanToInt(s + 2); if (strncmp(s, "IX", 2) == 0) return 9 + romanToInt(s + 2); if (strncmp(s, "IV", 2) == 0) return 4 + romanToInt(s + 2); if (s[0] == 'M') return 1000 + romanToInt(s + 1); if (s[0] == 'D') return 500 + romanToInt(s + 1); if (s[0] == 'C') return 100 + romanToInt(s + 1); if (s[0] == 'L') return 50 + romanToInt(s + 1); if (s[0] == 'X') return 10 + romanToInt(s + 1); if (s[0] == 'V') return 5 + romanToInt(s + 1); if (s[0] == 'I') return 1 + romanToInt(s + 1); return 0;