一、题目描述
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
题目解读:将数值表示成罗马数字的形式
思路:先要清楚罗马数字的表示规则
罗马数字共有七个:I(1),V(5),X(10),L(50),C(100),D(500),M(1000),规则如下:
(1)一个罗马数字重复几次,就表示这个数的几倍
(2)在一个较大的罗马数字的右边记上一个较小的罗马数字,表示大数字加小数字。在一个较大的数字的左边记上一个较小的罗马数字,表示大数字减小数字。但是左减不能跨越等级。比如99不可以用IC表示,要用XCIX表示。
(3)基本数字I、X、C中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目都不能超过三个,比如40不能表示为XXXX,而要表示成XL。放在大数的左边只能用一个。
(4)不能把基本数字V、L、D中的任何一个座位小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目、只能使用一个。
(5)I 只能用在 V 和 X 左边
(6)X 只能用在 L 和 C 左边
(7)C 只能用在 D 和 M 左边
c++代码(28ms,85.27%)
class Solution {
public:
string intToRoman(int num) {
string result;
while(num){
if(num>=1000){
result.push_back('M');
num -= 1000;
}else if(num >=900){
result += "CM";
num -= 900;
}else if(num >= 500){
result.push_back('D');
num -= 500;
}else if(num >= 400){
result += "CD";
num -= 400;
}else if(num >= 100){
result.push_back('C');
num -= 100;
}else if(num >= 90){
result += "XC";
num -= 90;
}else if(num >= 50){
result.push_back('L');
num -= 50;
}else if(num >= 40){
result += "XL";
num -= 40;
}else if(num >= 10){
result.push_back('X');
num -= 10;
}else if(num >= 9){
result += "IX";
num -= 9;
}else if(num >= 5){
result.push_back('V');
num -= 5;
}else if(num >= 4){
result += "IV";
num -= 4;
}else{
result.push_back('I');
num -= 1;
}
}//while
return result;
}
};
另一种写法(32ms,65.27%)
class Solution {
public:
string intToRoman(int num) {
int number[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string str[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int i=0;
string result;
while(num){
if(num >= number[i]){
result += str[i];
num -= number[i];
}else{
i++;
}
}//while
return result;
}
};