Integer to Roman(Medium)

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 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;  
    }

罗马数字转整数

// if previous character is greater than current character, we add the value of current charater,

// else we subtract the previous char twice(since we added it once).

public int romanToInt(String s) {
    if(s == null || s.length() == 0){
        return 0;
    }
    int pre = charToInt(s.charAt(0));
    int sum = pre;
    for(int i = 1; i < s.length(); i++){
        int cur = charToInt(s.charAt(i));
        if(pre < cur){
            sum -= 2*pre;
        }
        sum += cur;
        pre = cur;
    }
    return sum;
}

public int charToInt(char cha){
    switch(cha){
        case 'I': return 1;
        case 'V': return 5;
        case 'X': return 10;
        case 'L': return 50;
        case 'C': return 100;
        case 'D': return 500;
        case 'M': return 1000;
    }
    return 0;

}

results matching ""

    No results matching ""