- #include <list>
- #include <string>
- #include <cassert>
- #include <iostream>
- using namespace std;
- char a[]="OIVXLCDM";
- string toString(int n)
- {
- char s[10];
- string str;
- itoa(n,s,10);
- str+=s;
- return str;
- }
- string toRoman(int i)
- {
- //罗马数字不能表示0,也不足以表示比3999大的数
- assert(i>0 && i<=3999);
- string str=toString(i);
- list<string> r;
- for(int i=str.size()-1,j=1;i>=0;--i,j+=2)
- {
- if(str[i]=='0')
- {
- //r.push_front(string(1,a[0]));
- }
- else if(str[i]<='3')
- {
- string tmp(str[i]-'0',a[j]);
- r.push_front(tmp);
- }
- else if(str[i]=='4')
- {
- string tmp(1,a[j]);
- tmp+=a[j+1];
- r.push_front(tmp);
- }
- else if(str[i]=='5')
- {
- string tmp(1,a[j+1]);
- r.push_front(tmp);
- }
- else if(str[i]<='8')
- {
- string tmp(1,a[j+1]);
- tmp+=string(str[i]-'5',a[j]);
- r.push_front(tmp);
- }
- else
- {
- string tmp(1,a[j]);
- tmp+=a[j+2];
- r.push_front(tmp);
- }
- }
- string ret;
- for(list<string>::iterator it=r.begin();it!=r.end();++it)
- {
- if(it==r.begin())
- {
- ret+=*it;
- }
- else
- {
- ret+=' '+*it;
- }
- }
- return ret;
- }
- int main ()
- {
- cout<<toRoman(1984)<<endl;
- cout<<toRoman(3999)<<endl;
- cout<<toRoman(3888)<<endl;
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/291120137614.html
来源: http://www.codesnippet.cn/detail/291120137614.html