Given an integer, convert it to a roman numeral.

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

Symbol I V X L C D M
Value 1 5 10 50 100 500 1,000
Number 4 9 40 90 400 900
Notation IV IX XL XC CD CM
    public String intToRoman(int n) {
        // 注意4和9
        int tens = 1000;
        StringBuilder sb = new StringBuilder();
        while(tens != 0){
            int num = n / tens;
            if(tens == 1000){
                add('M', num, sb);
            } else if(tens == 100){
                if(num == 4){
                    sb.append("CD");
                } else if(num == 9){
                    sb.append("CM");
                } else{
                    add('C', num, sb);
                }
            } else if(tens == 10){
                if(num == 4){
                    sb.append("XL");
                } else if(num == 9){
                    sb.append("XC");
                } else{
                    add('X', num, sb);
                }
            } else if(tens == 1){
                if(num == 4){
                    sb.append("IV");
                } else if(num == 9){
                    sb.append("IX");
                } else{
                    add('I', num, sb);
                }
            }
            n %= tens;
            tens /= 10;
        }
        return sb.toString();
    }
    private void add(char c, int n, StringBuilder sb){
        int start = 0;
        if(n >= 5){
            if(c == 'C'){
                sb.append('D');
            } else if(c == 'X'){
                sb.append('L');
            } else if(c == 'I'){
                sb.append('V');
            }
            start = 5;
        }
        for(int i = start; i < n; i++){
            sb.append(c);
        }
    }

results matching ""

    No results matching ""