class Solution {
public:
string intToRoman(int num) {
int i=0;
string ret;
int a[]={1000,900,500,400,100,90,50,40,10,9,5,4,1}; //枚举每一个数字
const char *p[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
//每个数字对应的罗马数字
for(i=0;i<13;i++){
while(num>=a[i]){ //将num与由大到小的数字比较
num-=a[i]; //num减掉符合的数,不等于0时继续循环
ret.append(p[i]); //将结果存进去
}
if(num==0)
break;
}
cout<<0;
return ret;
}
};
按升序枚举每个数值对应的罗马数字存入数组中,对数组从头开始遍历,当输入的数值大于等于该数组所存储的数字时不断减直到并将对应的罗马数字存入字符串中。