Question:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
分析:
此问题首先要了解罗马数字规则(详见C++分类中的文章《罗马数字转换成阿拉伯数字》)
根据规则可以知道,当4,5,9,40,50,90,400,500,900时候是比较特殊的,需要判断是否为这些数据。
两种方法:
1、暴力法,依次判断是1000 ,100,10,1的多少倍,然后在其中判断4,5,9等的位置;
2、将4,5,9等特殊数据也提前声明好罗马数字,然后依次判断是1000,900,500,400,100,90,50,40,10,9,5,4,1的多少倍即可。
代码如下:
<span style="font-size:14px;">class Solution {
public:
string intToRoman(int num) {
string res = "";
string data[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int value[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
int base = -1;
for(int i = 0; i < 13; i++){
if((base = num/value[i]) != 0){
while(base-- != 0)
res += data[i];
num %= value[i];
}
}
return res;
//暴力法
//string res = "";
/* unordered_map<int,string> maps;
maps[1] = "I";
maps[5] = "V";
maps[10] = "X";
maps[50] = "L";
maps[100] = "C";
maps[500] = "D";
maps[1000] = "M";
if(num < 1 || num > 3999)
return res;
if(num / 1000 != 0){
int cnt = num / 1000;
for(int i = 0; i < cnt; ++i){
res += maps[1000];
}
num %= 1000;
}
if(num / 100 != 0){
int cnt = num / 100;
if(cnt < 4){
for(int i = 0; i < cnt; ++i){
res += maps[100];
}
}
else{
if(cnt == 4){
res += (maps[100] + maps[500]);
}
else{
if(cnt == 9){
res += (maps[100] + maps[1000]);
}
else{
int n = cnt - 5;
res += maps[500];
for(int j = 0; j < n; ++j){
res += maps[100];
}
}
}
}
num %= 100;
}
if(num / 10 != 0){
int cnt = num / 10;
if(cnt < 4){
for(int i = 0; i < cnt; ++i){
res += maps[10];
}
}
else{
if(cnt == 4){
res += (maps[10] + maps[50]);
}
else{
if(cnt == 9){
res += (maps[10] + maps[100]);
}
else{
int n = cnt - 5;
res += maps[50];
for(int j = 0; j < n; ++j){
res += maps[10];
}
}
}
}
num %= 10;
}
int cnt = num;
if(cnt < 4){
for(int i = 0; i < cnt; ++i){
res += maps[1];
}
}
else{
if(cnt == 4){
res += (maps[1] + maps[5]);
}
else{
if(cnt == 9){
res += (maps[1] + maps[10]);
}
else{
int n = cnt - 5;
res += maps[5];
for(int j = 0; j < n; ++j){
res += maps[1];
}
}
}
}
return res;*/
}
};</span>