leetcode 12题 数字转罗马数字
答案一:我的代码
代码本地运行完全正确,在线运行出错
1 class Solution { 2 public: 3 string intToRoman(int num) { 4 5 //哈希表初始化; 6 unordered_map<int,char>hash; 7 string str_initial1="IXCM"; 8 string str_initial2="VLD"; 9 int index=0; 10 for(int i=1;i<=1000;i*=10){ 11 hash[i]=str_initial1[index]; 12 index++; 13 } 14 index=0; 15 for(int i=5;i<=500;i*=10){ 16 hash[i]=str_initial2[index]; 17 index++; 18 } 19 20 //通过哈希表和取余数来进行倒序获取罗马字符 21 string s,re; 22 int temp=num; 23 int cnt=1; 24 index=0; 25 while(temp>0){ 26 int pop=temp%10; 27 temp=temp/10; 28 if(pop==0){cnt*=10;continue;} 29 else if(pop==9){ 30 s[index++]=hash[cnt*10]; 31 s[index++]=hash[cnt]; 32 }else if(pop==4){ 33 s[index++]=hash[cnt*5]; 34 s[index++]=hash[cnt]; 35 }else{ 36 int flag=0; 37 if(pop>4){ 38 flag=1; 39 pop=pop-5; 40 } 41 for(int i=0;i<pop;i++){ 42 s[index++]=hash[cnt]; 43 } 44 if(flag==1){ 45 s[index++]=hash[cnt*5]; 46 } 47 } 48 cnt=cnt*10; 49 } 50 //cout<<index<<endl; 51 for(int i=0;i<index;i++){ 52 re[i]=s[index-i-1]; 53 } 54 return re; 55 } 56 };
答案二:
参考别人将预先的特殊情况(即罗马数字符号进位与罗马数字前后大小颠倒两种情况全部事先存储起来,然后根据实际情况进行计算)
class Solution { public: string intToRoman(int num) { vector<int> val={1000,900,500,400,100,90,50,40,10,9,5,4,1}; vector<string> rom={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int i=0; string re=""; for(int i=0;i<val.size();i++){ while(num>=val[i]){ re+=rom[i]; num-=val[i]; } } return re; } };