问题描述
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
思路分析
给一个1-3999的整数,将其转化为罗马数字的字符串。
用一个极为丑陋的方式解决,将满足不同的条件的if语句放入循环中,每次减去相应的数值,直到num变为0;
代码
class Solution {
public:
string intToRoman(int num) {
string result = "";
while (num != 0){
if (num >= 1000){
num -= 1000;
result += "M";
continue;
}
if (num >= 900){
num -= 900;
result += "CM";
continue;
}
if (num >= 500){
num -= 500;
result += "D";
continue;
}
if (num >= 400){
num -= 400;
result += "CD";
continue;
}
if (num >= 100){
num -= 100;
result += "C";
continue;
}
if (num >= 90){
num -= 90;
result += "XC";
continue;
}
if (num >= 50){
num -= 50;
result += "L";
continue;
}
if (num >= 40){
num -= 40;
result += "XL";
continue;
}
if (num >= 10){
num -= 10;
result += "X";
continue;
}
if (num == 9){
num -= 9;
result += "IX";
continue;
}
if (num >= 5){
num -= 5;
result += "V";
continue;
}
if (num == 4){
num -= 4;
result += "IV";
continue;
}
if (num >= 1){
num -= 1;
result += "I";
continue;
}
}
return result;
}
};
时间复杂度:
O(logn)
空间复杂度:
O(1)
反思
看到一样丑陋的代码我就放心了,但是人家的方法还是比我巧妙的,把每一种的情况都考虑到了。
class Solution {
public:
const static string THOUS[];
const static string HUNDS[];
const static string TENS[];
const static string ONES[];
string intToRoman(int num) {
string result;
result += THOUS[(int)(num/1000)%10];
result += HUNDS[(int)(num/100)%10];
result += TENS[(int)(num/10)%10];
result += ONES[num%10];
return result;
}
};
const string Solution::THOUS[] = {"","M","MM","MMM"};
const string Solution::HUNDS[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
const string Solution::TENS[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
const string Solution::ONES[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};