算法分析與設計課程(16):【leetcode】 Integer to Roman

Description:

Given an integer, convert it to a roman numeral.

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

Subscribe to see which companies asked this question.

算法分析:

羅馬數字的規則:

  1. 字符:M=1000, D=500, C=100, L=50, X=10, V=5, I=1.

  2. 按序累加即可。

  3. {1,5} * 10^i, 在千這個範圍的規則字符數

  4. 考慮字符的下一位的最小值,比如{4,9}*10^i, 是通過把小字符放在大字符前面(相減)來表示的,其他的是直接重複。

按照如上規則,從大向小逐個打印並削減即可。由於只有三層,下面的代碼直接硬coding完成。也可以做成table,然後for循環完成,只需要實現一層的場景。

代碼如下:

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章