12,13罗马数字转来转去

这题thumps down怎么这么多,反正叫我徒手写是不可能写得出来的,记下来吧
首先要直到罗马数字和阿拉伯数字的转换规则:


12,13罗马数字转来转去_第1张图片
image.png
  1. Integer to Roman
class Solution {
    // I    1    
    // V    5    
    // X    10   
    // L    50   
    // C    100  
    // D    500  
    // M    1000    
    public String intToRoman(int num) {
        String M[] = {"", "M","MM","MMM"};
        String C[] = {"", "C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
        String X[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
        String I[] = {"", "I","II","III","IV","V","VI","VII","VIII","IX"};
        return M[num/1000] + C[num%1000/100] + X[num%100/10] + I[num%10];
    }
}
  1. Roman to Integer
    很少写switch case, 注意一下syntax:
switch (variable){
  case 'v1':
    do sth;
    break;
  case 'v1':
    do sth;
    break;
}
class Solution {
    public int romanToInt(String s) {
        int res = 0;
          // I  1    
        // V    5    
        // X    10   
        // L    50   
        // C    100  
        // D    500  
        // M    1000
        //"XXIV"
        //"XXII"
        for (int i = s.length() - 1; i >= 0; i--){
            char c = s.charAt(i);
            switch (c) {
                case 'I':
                    res += (res >= 5 ? -1 : 1);
                    break;
                case 'V':
                    res += 5;
                    break;
                case 'X':
                    res += (res >= 50 ? -10 : 10);
                    break;
                case 'L':
                    res += 50;
                    break;
                case 'C':
                    res += (res >= 500 ? -100 : 100);
                    break;
                case 'D':
                    res += 500;
                    break;
                case 'M':
                    res += 1000;
                    break;
            }
        }
        return res;
    }
}

你可能感兴趣的:(12,13罗马数字转来转去)