My solution with arrays


  • 0

    It's only a little trick. Just for fun.

    public int romanToInt(String s) {
            // I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1,000
            Character[] roman = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
            int[] number = {1, 5, 10, 50, 100, 500, 1000};
            
            int ret = 0, old = 0;
            for(int i = s.length() - 1; i >= 0; i --){
                Character temp = s.charAt(i);
                for(int j = 0; j < roman.length; j ++){
                    if(temp == roman[j]){
                        if(number[j] >= old)
                            ret += number[j];
                        else
                            ret -= number[j];
                        old = number[j];
                    }
                }
            }
            return ret;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.