标签:href public ref .com src 时间复杂度 toc while leetcode
目录
解法一:从大到小考虑1000,900,500,400,100,90,50,40,10,9,5,4,1这些数字,大于就减去,直到为0。时间复杂度为O(n)
class Solution {
public:
string intToRoman(int num) {
string ans = "";
while(num > 0)
{
if(num >= 1000)
{
ans += "M";
num -= 1000;
}
else if(num >= 900)
{
ans += "CM";
num -= 900;
}
else if(num >= 500)
{
ans += "D";
num -= 500;
}
else if(num >= 400)
{
ans += "CD";
num -= 400;
}
else if(num >= 100)
{
ans += "C";
num -= 100;
}
else if(num >= 90)
{
ans += "XC";
num -= 90;
}
else if(num >= 50)
{
ans += "L";
num -= 50;
}
else if(num >= 40)
{
ans += "XL";
num -= 40;
}
else if(num >= 10)
{
ans += "X";
num -= 10;
}
else if(num >= 9)
{
ans += "IX";
num -= 9;
}
else if(num >= 5)
{
ans += "V";
num -= 5;
}
else if(num >= 4)
{
ans += "IV";
num -= 4;
}
else if(num >= 1)
{
ans += "I";
num -= 1;
}
}
return ans;
}
};
标签:href public ref .com src 时间复杂度 toc while leetcode
原文地址:https://www.cnblogs.com/multhree/p/10327994.html