题目来源
解题方法
贪心哈希
class Solution {
public:
string intToRoman(int num) {
int value[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};
string roman[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
string res="";
int i=0;
while(num!=0){
if(num>=value[i]){
num-=value[i];
res+=roman[i];
} else {
i++;
}
}
return res;
}
};
暴力按位
class Solution {
public:
string intToRoman(int num) {
string roman[4][10]={
{"","I","II","III","IV","V","VI","VII","VIII","IX"},
{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
{"","M","MM","MMM"}
};
string str;
str.append(roman[3][num/1000]);
str.append(roman[2][num%1000/100]);
str.append(roman[1][num/10%10]);
str.append(roman[0][num%10]);
return str;
}
};