Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
网上都比较喜欢用recursion,我个人觉得脱了裤子放屁。。。。
class Solution {
public:
string intToRoman(int num) {
string thousands[] = {"", "M", "MM", "MMM"};
string hundreds[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
string tens[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
string ones[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return thousands[num/1000]+hundreds[(num/100)%10]+tens[(num/10)%10]+ones[num%10];
}
};
网上的答案超一遍,学习。。。
class Solution {
public:
string intToRoman(int num) {
static int vals[]= {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
static string refs[]={"M", "CM", "D", "CD", "C", "XC", "L", "XL","X","IX","V","IV","I" };
int size=sizeof(vals)/sizeof(int);
for(int i=0;i<size;i++){
if(vals[i]<=num)
return refs[i]+intToRoman(num-vals[i]);
}
return "";
}
};
略无聊。。。。