我的解法 疯狂用if else判断
我靠看了题解,发现我是真不懂脑子。虽然过了,但是代码真就是那种又简单又蠢的。我懒得解释了,看一眼就能明白.但凡稍微思考下都不至于写出这么啰嗦的代码!!!
class Solution
{
public:
string intToRoman(int num)
{
string roman_str;
// 处理千位
// num > 1000
if (num >= 1000)
{
int M = num / 1000;
num %= 1000;
roman_str.insert(0, M, 'M');
}
//cout << roman_str << endl;
// 处理百位
// 900 <= num < 1000
while (num >= 100)
{
if (num >= 900)
{
roman_str = roman_str + "CM";
num -= 900;
}
// 500 <= num < 900
else if (num >= 500)
{
roman_str += "D";
num -= 500;
}
// 400 <= num < 500
else if (num >= 400)
{
roman_str += "CD";
num -= 400;
}
// 100 <= num < 400
else
{
int C = num / 100;
num %= 100;
roman_str.insert(roman_str.end(), C, 'C');
}
}
//cout << roman_str << endl;
// 处理十位数
while (num >= 10)
{
// 90 <= num < 100
if (num >= 90)
{
roman_str += "XC";
num -= 90;
}
else if (num >= 50)
{
roman_str += "L";
num -= 50;
}
// 40 <= num < 90
else if (num >= 40)
{
roman_str += "XL";
num -= 40;
}
// num < 40
else
{
int X = num / 10;
num %= 10;
roman_str.insert(roman_str.end(), X, 'X');
}
}
//cout << roman_str << endl;
// 处理个位数
// num = 9
if (num == 9)
{
roman_str += "IX";
}
else if (num >= 5)
{
roman_str += "V";
roman_str.insert(roman_str.end(), num - 5, 'I');
}
// 4 <= num < 9
else if (num >= 4)
{
roman_str += "IV";
roman_str.insert(roman_str.end(), num - 4, 'I');
}
// num < 4
else
{
roman_str.insert(roman_str.end(), num, 'I');
}
//cout << roman_str << endl;
return roman_str;
}
};

别人的解法 hashMap加贪心
woc,这才叫干净清爽的代码,虽然意思也是我那个意思,但是代码好看太多了。代码含义也很简单,稍微一看就能看懂,不解释了
class Solution1
{
public:
string intToRoman(int num)
{
int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string reps[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
string res;
// 这里的13为hash表的长度
for (int i = 0; i < 13; i++)
while (num >= values[i])
{
num -= values[i];
res += reps[i];
}
return res;
}
};
作者:z1m
链接:https://leetcode-cn.com/problems/integer-to-roman/solution/tan-xin-ha-xi-biao-tu-jie-by-ml-zimingmeng/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。