您的位置:首页 > 其它

12. Integer to Roman

2018-03-14 05:33 323 查看

问题描述

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[]   = {
a355
"","I","II","III","IV","V","VI","VII","VIII","IX"};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: