12. Integer to Roman

題目

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

分析

首先查了下羅馬數(shù)字的書(shū)寫(xiě)規(guī)則
https://www.douban.com/note/335254352/
發(fā)現(xiàn)可以從大到小依次書(shū)寫(xiě),比較簡(jiǎn)單,不多說(shuō)直接上代碼。

實(shí)現(xiàn)

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

思考

這里我比較懶,就直接用了若干循環(huán)完成了。
其實(shí),還可以將這些循環(huán)兩兩分為一組,放入一個(gè)大循環(huán)內(nèi)。
或者直接將兩個(gè)字母的組合例如“IX”等變?yōu)樾碌囊粋€(gè)單元,這樣更簡(jiǎn)單。
另外更討巧的方法可以是把個(gè)十百千位的各種情況都列出來(lái),這樣可以直接輸出,代碼如下。

class Solution {
public:
    string intToRoman(int num) {
        char* digit[10] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
        char* ten[10] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
        char* hundreds[10] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        char* thousand[4] = {"","M","MM","MMM"};
        
        string answer = "";
        answer = answer + thousand[num/1000] + hundreds[(num/100)%10] + ten[(num/10)%10] + digit[(num)%10];
        return answer;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容