题目地址:https://leetcode-cn.com/problems/integer-to-roman/
解题思路: 打一个模板然后分情况讨论。写的比较丑。
map<int, string> mp; map<int, string> ::iterator it; class Solution { public: string resolve(int xnum,int x,int flag) { string s = ""; if (xnum >= 0) { if (xnum == 4) s += mp[9 * flag]; else { s += mp[5 * flag]; while (xnum--) s += mp[1 * flag]; } } else if (x == 4) s+=mp[4*flag]; else while (x--) s+=mp[1*flag]; return s; } string intToRoman(int num) { int index[13] = { 1,4,5,9,10,40,50,90,100,400,500,900,1000 }; string tmp[13] = { "I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M" }; string sReturn = ""; for (int i = 0; i < 13; i++) mp[index[i]] = tmp[i]; if (mp.find(num) != mp.end()) sReturn += mp[num]; else { int g=num%10;//个位数 int gnum = g - 5;//输出次数 int s = num / 10 % 10;//十位数 int snum = s - 5;//输出次数 int b = num / 100 % 10;//百位数 int bnum = b - 5;//输出次数 int q= num / 1000 ;//千位数 while (q--) sReturn += mp[1000]; sReturn+=resolve(bnum, b, 100); sReturn+=resolve(snum, s , 10); sReturn+=resolve(gnum, g, 1); } return sReturn; } };