【LeetCode刷题记录】12. 整数转罗马数字

题目描述:
在这里插入图片描述
在这里插入图片描述
题解:
两种解法,思路都比较简单,第二种比较有意思。
一、暴力法(时间复杂度O(1),空间复杂度O(1))

string intToRoman(int num)
{
 string result;
 vector<string> tmpVec1 = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
 vector<string> tmpVec2 = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
 vector<string> tmpVec3 = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
 vector<string> tmpVec4 = { "", "M", "MM", "MMM" };
 vector<vector<string>> store = { tmpVec1, tmpVec2, tmpVec3, tmpVec4 };
 result.append(store[3][num / 1000 % 10]);
 result.append(store[2][num / 100 % 10]);
 result.append(store[1][num / 10 % 10]);
 result.append(store[0][num % 10]);
 return result;
}

二、贪心法

string intToRoman(int num)
{
 string result;
 vector<int> store = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
 vector<string> strs = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
 int storeSize = int(store.size());
 for (int i = 0; i < storeSize; i++)
 {
  while (num >= store[i])
  {
   result.append(strs[i]);
   num -= store[i];
  }
 }
 return result;
}
原创文章 23 获赞 0 访问量 982

猜你喜欢

转载自blog.csdn.net/weixin_42192493/article/details/105241443
今日推荐