Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
思路
同样,注意4和9的处理就行了。仍然是从末位处理比较方便。
class Solution {
public:
string intToRoman(int num) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(num<=0) return "";
if(num>=4000) return "";
int numb=num;
char con[]={'I','V','X','L','C','D','M','\0'};
char buff[16]={'\0'};
int pos=0;
int posb=0;
while(numb!=0)
{
int digit=numb%10;
if(digit<=3) while(digit-->0) buff[posb++]=con[pos*2];
else if(digit==4){buff[posb++]=con[pos*2+1];buff[posb++]=con[pos*2];}
else if(digit==5){buff[posb++]=con[pos*2+1];}
else if(digit<=8){while(digit-->5) buff[posb++]=con[pos*2];buff[posb++]=con[pos*2+1];}
else if(digit==9){buff[posb++]=con[pos*2+2];buff[posb++]=con[pos*2];}
numb/=10;
pos++;
}
int bLen=strlen(buff);
for(int i=0;i<bLen/2;i++)
{
int tmp=buff[i];
buff[i]=buff[bLen-i-1];
buff[bLen-i-1]=tmp;
}
return string(buff);
}
};

本文介绍了一种将整数转换为罗马数字的算法,通过遍历字符数组并根据数值进行拼接,确保了从末位处理的便利性。特别注意4和9的特殊处理方式。
397

被折叠的 条评论
为什么被折叠?



