if写法
把4,9单独区分出来
string str;
int s1 = num / 1000;
for (int i = 0; i < s1; i++)
str+='M';
int s2 = (num % 1000) / 100;
if (s2 == 9)
str+= "CM";
else if (s2 == 4)
str += "CD";
else if (s2 >= 5)
{
str += 'D';
for (int i = 0; i < s2 - 5; i++)
str += 'C';
}
else
for (int i = 0; i < s2; i++)
str += 'C';
int s3 = (num % 100) / 10;
if (s3== 9)
str += "XC";
else if (s3 == 4)
str += "XL";
else if (s3 >= 5)
{
str += 'L';
for (int i = 0; i < s3- 5; i++)
str += 'X';
}
else
for (int i = 0; i < s3; i++)
str += 'X';
int s4 = (num % 10);
if (s4 == 9)
str += "IX";
else if (s4 == 4)
str += "IV";
else if (s4 >= 5)
{
str += 'V';
for (int i = 0; i < s4 - 5; i++)
str += 'I';
}
else
for (int i = 0; i < s4; i++)
str += 'I';
cout << str;
return 0;
减法思路
因为用罗马数字表示整数势必要从大到小取罗马数,所以可以建立一个对应表后,用要表示的整数依次减去罗马标准数,并且添加一个标志记录减去的标准数,以整数小于这个标准数为中止条件(太聪明了,我怎么就没想到)
代码(复制粘贴来自力扣)
const pair<int, string> valueSymbols[] = {
{1000, "M"},
{900, "CM"},
{500, "D"},
{400, "CD"},
{100, "C"},
{90, "XC"},
{50, "L"},
{40, "XL"},
{10, "X"},
{9, "IX"},
{5, "V"},
{4, "IV"},
{1, "I"},
};
class Solution {
public:
string intToRoman(int num) {
string roman;
for (const auto &[value, symbol] : valueSymbols) {
while (num >= value) {
num -= value;
roman += symbol;
}
if (num == 0) {
break;
}
}
return roman;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/integer-to-roman/solutions/774611/zheng-shu-zhuan-luo-ma-shu-zi-by-leetcod-75rs/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
结论:有排序并且耦合迹象的题目从遍历角度思考