[leetcode] 12. Integer to Roman

关于罗马数字:

I: 1
V: 5
X: 10
L: 50
C: 100
D: 500
M: 1000

字母可以重复,但不超过三次,当需要超过三次时,用与下一位的组合表示:
I: 1, II: 2, III: 3, IV: 4
C: 100, CC: 200, CCC: 300, CD: 400

提取每一位digit,然后convert to 罗马数字

public class Solution {
    private static char[][] chars = {{'I', 'V'}, {'X', 'L'}, {'C', 'D'}, {'M', 'O'}};
    public String intToRoman(int num) {
        int copy_num = num;
        int count = 0;
        StringBuilder result = new StringBuilder();
        while (copy_num != 0) {
            int x = copy_num / 10;
            int digit = copy_num - x * 10;
            switch (digit) {
                case 3: result.append(chars[count][0]);
                case 2: result.append(chars[count][0]);
                case 1: result.append(chars[count][0]);
                case 0: break;
                case 4: result.append(chars[count][1]); result.append(chars[count][0]); break;
                case 8: result.append(chars[count][0]);
                case 7: result.append(chars[count][0]);
                case 6: result.append(chars[count][0]); 
                case 5: result.append(chars[count][1]); break;
                case 9: result.append(chars[count + 1][0]); result.append(chars[count][0]); break;
            }
            count++;
            copy_num = x;
        }
        
        result = result.reverse();
        return result.toString();
    }
}

 

posted @ 2016-12-27 08:46  Gryffin  阅读(144)  评论(0编辑  收藏  举报