DAY 14
0

## Day19 #12 #13 Integer and Roman Conversion

12題 → 數字轉羅馬數字
13題 → 羅馬數字轉數字

### 程式碼

12題

``````class Solution {
public:
string intToRoman(int num) {

string ans="";
while(num!=0)
{
if(num>=1000)
{
ans+="M";
num-=1000;
}
else if(num>=900)
{
ans+="CM";
num-=900;
}
else if(num>=500)
{
ans+="D";
num-=500;
}
else if(num>=400)
{
ans+="CD";
num-=400;
}
else if(num>=100)
{
ans+="C";
num-=100;
}
else if(num>=90)
{
ans+="XC";
num-=90;
}
else if(num>=50)
{
ans+="L";
num-=50;
}
else if(num>=40)
{
ans+="XL";
num-=40;
}
else if(num>=10)
{
ans+="X";
num-=10;
}
else if(num>=9)
{
ans+="IX";
num-=9;
}
else if(num>=5)
{
ans+="V";
num-=5;
}
else if(num>=4)
{
ans+="IV";
num-=4;
}
else
{
ans+="I";
num-=1;
}
}
return ans;
}
};
``````

13題

``````class Solution {
public:
int romanToInt(string s) {
int ans=0;
for(int i=0;i<s.length();)
{
if(s[i]=='M')
{ans+=1000;i++;}
else if(s[i]=='C'&&s[i+1]=='M')
{ans+=900;i+=2;}
else if(s[i]=='D')
{ans+=500;i++;}
else if(s[i]=='C'&&s[i+1]=='D')
{ans+=400;i+=2;}
else if(s[i]=='C')
{ans+=100;i++;}
else if(s[i]=='X'&&s[i+1]=='C')
{ans+=90;i+=2;}
else if(s[i]=='L')
{ans+=50;i++;}
else if(s[i]=='X'&&s[i+1]=='L')
{ans+=40;i+=2;}
else if(s[i]=='X')
{ans+=10;i++;}
else if(s[i]=='I'&&s[i+1]=='X')
{ans+=9;i+=2;}
else if(s[i]=='V')
{ans+=5;i++;}
else if(s[i]=='I'&&s[i+1]=='V')
{ans+=4;i+=2;}
else if(s[i]=='I')
{ans+=1;i++;}
}
return ans;
}
};
``````

### 心路歷程

(我自己私下以為可能是我自己前幾天瘋狂吃辣(辣椒配飯、吐司夾辣椒...等)引起的發炎)
(但他們貌似是以為是我弟帶回家的腸胃病毒???嗯....避免被罵，這可是個秘密)