Simple Java looping Solution


  • 0
    C
    public class Solution {
        public int romanToInt(String s) {
            
            int[] map = new int[24];
            map['M' - 'A'] = 1000;
            map['C'- 'A'] = 100;
            map['D' - 'A'] = 500;
            map['L' - 'A'] = 50;
            map['X'- 'A'] = 10;
            map['V'- 'A'] = 5;
            map['I' - 'A'] = 1;
            int num = 0, i=0, len = s.length();
            while(i<len){
                if(i+1<len && map[s.charAt(i)- 'A'] < map[s.charAt(i+1)-'A']){
                    num+=  map[s.charAt(i+1)- 'A'] - map[s.charAt(i)- 'A'];
                    i= i+2;
                }
                else{
                    num+= map[s.charAt(i)- 'A'];
                    i++;
                }
            }
            
            return num;
            
        }
    }
    

Log in to reply
 

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