[leetcode] 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.
題意:
給定一個數字,轉化爲羅馬數字。
思路:
我們先打表,將個十百千位上整數對應的羅馬數字打出。然後每一位只要從表中取就行了。
代碼如下:

class Solution {
public:
    string intToRoman(int num) {
        string table[30] = {"I","II","III","IV","V","VI","VII","VIII","IX",
                            "X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
                            "C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
                            "M","MM","MMM"    
                             };
        int temp = num;
        int count = 0;
        while(temp > 0) {
            count++;
            temp /= 10;
        }
        int high = pow(10, count - 1);
        string result = "";
        while(num > 0) {
            int index = num / high;
            result = (index > 0)?result + table[(count - 1)*9 + index - 1]:result;
            num %= high;
            high /= 10;
            count--;
        }
        return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章