Leetcode#12Integer to Roman

Integer to Roman

 Total Accepted: 31922 Total Submissions: 91429My Submissions

Question Solution 


Given an integer, convert it to a roman numeral.

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


Show Tags

Have you met this question in a real interview? 

Yes

 

No

Discuss


【題目】

Given a roman numeral, convert it to an integer. Or, Given an integer, convert it to a roman numeral.

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

【羅馬數字】

1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};

10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};

100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};

1000~3000: {"M", "MM", "MMM"}.


public class Solution {

    public String intToRoman(int num) {

        String[][] roman = {  

            {"", "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"}  

        };  

          

        String ret = "";  

        int digit = 0;  

        while (num != 0) {  

            int remain = num % 10;  

            ret = roman[digit][remain] + ret;  

            digit++;  

            num /= 10;  

        }  

          

        return ret;  

    }

}


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