leetcode -- Integer to Roman

Given an integer, convert it to a roman numeral.

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

 

 1 public String intToRoman(int num) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         StringBuffer result = new StringBuffer();
 5         String[][] mapping = {
 6                 {"", "M", "MM", "MMM", "", "", "", "", "", ""}, //0 – 3000
 7                 {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, //100 – 900
 8                 {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, //10 – 90
 9                 {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"} //0 – 9    
10         };
11         int scale = 1000;
12         int i = 0;
13         while(num > 0){
14             int digit = num / scale;
15             result.append(mapping[i++][digit]);
16             num = num % scale;
17             scale /= 10;
18         }
19         return result.toString();
20     }

 

posted @ 2013-09-04 22:31  feiling  阅读(240)  评论(0编辑  收藏  举报