GEEK编程练习— —罗马数字问题
2016-06-07 15:57
337 查看
题目
输入的是一个整数或罗马数字,若为整数,输出对应的罗马数字;若为罗马数字,输出对应的整数。数值范围从1到3999。输入
1100
输出
MC
输入
MC
输出
1100
分析
因为输入只有两种情况,判断一下首个字符为整数还是罗马数字,分两种情况进行转换。代码
#include <iostream> #include <string> #include <cctype> #include <cstdlib> using namespace std; int R2IMap(const char c) { switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } } int main() { string str; cin >> str; if (isdigit(str[0])) { int num = atoi(str.c_str()); const int radix[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; const string symbol[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; string roman; for (int i = 0; num > 0; ++i) { int ncount = num / radix[i]; num %= radix[i]; for (; ncount > 0; --ncount) { roman += symbol[i]; } } cout << roman << endl; } else { int result = 0; for (int i = 0; i < str.size(); ++i) { if (i > 0 && R2IMap(str[i]) > R2IMap(str[i - 1])) { result += (R2IMap(str[i]) - 2 * R2IMap(str[i - 1])); } else { result += R2IMap(str[i]); } } cout << result << endl; } return 0; }