Problem C: Numeral System
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1137&lang=jp
ICPCの過去問
解法:解析->複合
#include<iostream> #include<cmath> #include<sstream> #include<string> using namespace std; //string型の数字をint型にして返すよ int s_to_int(string s) { stringstream ss; int n; ss << s; ss >> n; return n; } //cが1文字の整数かどうか返すよ bool num_check(char c){ return c >= 48 && c <= 57;} //文字ごとに桁数返すよ int check(char c) { if (c == 'm') { return 1000; }else if (c == 'c') { return 100; }else if (c == 'x') { return 10; }else { return 1; } } int main() { int n=0; cin >> n; for (int i=0; i < n; i++) { int sum = 0; //解析 for (int j=0; j < 2; j++) { string s; cin >> s; for (int k=0; k < s.size(); k++) { if (num_check(s[k])) { string hs = ""; hs += s[k]; int hn = s_to_int(hs); sum += hn * check(s[k+1]); k++; }else { sum += 1 * check(s[k]); } } } //sumを元に暗号化 int num[] = {0,0,0,0}; char c_num[] = {'m','c','x','i'}; int count = 0; for (int h = 1000; h != 1; h/=10) { if(sum >= h) { num[count] = (int) floor(sum / h); sum -= num[count] * h; } count++; } num[3] = (int) sum; string resurt = ""; for (int h=0; h < 4; h++) { if (num[h] >= 1) { if (num[h] != 1) resurt += num[h]+48; resurt += c_num[h]; } } cout << resurt << endl; } }