标签:
题目链接:http://acm.swust.edu.cn/problem/0666/
1
10
35
99
400
|
1=I
10=X
35=XXXV
99=XCIX
400=CD
|
1 #include<iostream> 2 using namespace std; 3 char key[20], X[] = " IXCMVLD";//数的五倍用i+4表示 4 int cnt; 5 void Rserve(int x){ 6 int i, cur = 0, k = 0, lp = 1; 7 while (x > cur){ 8 cur = 10 * cur + 9; 9 k++; 10 } 11 for (i = 1; i < k; i++, lp *= 10); 12 if (x <= 4 * lp - 1){ 13 for (i = 0; i < x / lp; i++) 14 key[cnt++] = X[k]; 15 } 16 else if (x <= 5 * lp - 1){ 17 key[cnt++] = X[k]; 18 key[cnt++] = X[k + 4]; 19 } 20 else if (x <= 9 * lp - 1){ 21 key[cnt++] = X[k + 4]; 22 for (i = 0; i < x / lp - 5; i++) 23 key[cnt++] = X[k]; 24 } 25 else{ 26 key[cnt++] = X[k]; 27 key[cnt++] = X[k + 1]; 28 } 29 if (x%lp) Rserve(x%lp); 30 } 31 int main(){ 32 int i, x; 33 while (cin >> x){ 34 cnt = 0; 35 Rserve(x); 36 cout << x << ‘=‘; 37 for (i = 0; i < cnt; i++) 38 cout << key[i]; 39 cout << endl; 40 } 41 return 0; 42 }
当然了这道题这么溜,直接分析数字的组成方式1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1,与这些数字相关联会发生比如3和4,8和9,之间数字构成有一个本质的变化,具体的看题目的规则吧,然后每一个数字对应一个罗马数字组合递归找就是了具体见下表
1000 | 900 | 500 | 400 | 100 | 90 | 50 | 40 | 10 | 9 | 5 | 4 | 1 |
M | CM | D | CD | C | XC | L | XL | X | IX | V | IV | I |
很溜的代码如下:
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 int x[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; 5 string L[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; 6 string exchange(int n){ 7 string s; 8 int i = 0; 9 while (n){ 10 if (n >= x[i]){ 11 n -= x[i]; 12 s += L[i]; 13 } 14 else 15 i++; 16 } 17 return s; 18 } 19 int main(){ 20 int n; 21 while (cin >> n){ 22 cout << n << ‘=‘; 23 cout << exchange(n) << endl; 24 } 25 return 0; 26 }
[Swust OJ 666]--初来乍到(题号都这么溜~~,递归,找规律)
标签:
原文地址:http://www.cnblogs.com/zyxStar/p/4582012.html