C++
用两个数组表示值和罗马,包括其中的特殊情况一一对应,一共13种
注意里面判断要用while循环,因为num减去一个数的时候还会小于上一个判断的数,罗马数字可能会连续重复,比如III
class Solution {
public:
string intToRoman(int num) {
int nums[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};
string res[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
string ans;
for(int i=0;i<13;i++){
while(num >= nums[i]){
num = num - nums[i];
ans = ans + res[i];
}
}
return ans;
}
};
Python
Python直接使用字典表示,for key,value in hasmap.items()循环键值对要用items
class Solution:
def intToRoman(self, num: int) -> str:
hasmap = {1000:'M',900:'CM',500:'D',400:'CD',100:'C',90:'XC',50:'L',40:'XL',10:'X',9:'IX',5:'V',4:'IV',1:'I'}
ans = ''
for key,value in hasmap.items():
while num >= key:
ans += value
num -= key
return ans