Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
string intToS(int cur,string s,int base,map<int,string> &mDic) { if(cur==9 || cur==4 || cur==5 || cur==1) s += mDic[cur*base]; else { if(cur>5) { s += mDic[5*base]; cur -= 5; } for(int i=0;i<cur;i++) s +=mDic[base]; } return s; } class Solution { public: string intToRoman(int num) { map<int,string> mDic; mDic[1]="I"; mDic[5]="V"; mDic[10]="X"; mDic[50]="L"; mDic[100]="C"; mDic[500]="D"; mDic[1000]="M"; mDic[4]="IV"; mDic[9]="IX"; mDic[40]="XL"; mDic[90]="XC"; mDic[400]="CD"; mDic[900]="CM"; int cur = 0,base; string s0 = ""; if(num>=1000)//处理千位 { cur = num/1000; for(int i=0;i<cur;i++) s0 += mDic[1000]; num -= cur*1000; } if(num>=100)//处理百位 { cur = num/100; num -= cur*100; base = 100; s0 = intToS(cur,s0,base,mDic); } if(num>=10)//处理十位 { cur = num/10; num -= cur*10; base =10; s0 = intToS(cur,s0,base,mDic); } if(num>0)//处理个位 { cur = num; base = 1; s0 = intToS(cur,s0,base,mDic); } return s0; } };
有可以使代码看起来更简单的方法,LeetCode的Discuss可以看一看。