roman to integer, Java solution


  • 0
    L

    The solution below is functional.

    • romanMapInt is a helper function that has a switch statement that maps each single Roman numeral to its int value;
      I → 1
      V → 5
      X → 10
      L → 50
      C → 100
      D → 500
      M → 1000

    Let curr = current numeral, and prev = previous numeral for the purpose of this explanation.

    • romanToInt iterates through each character in String s. Notice that Roman numerals are always in the order of greatest to least (curr <= prev), except in the case of 4, 40, 400, etc. For these exceptional numbers, a smaller numeral comes before a larger one to symbolize subtraction.

    We can pretty much extrapolate this observation into the following rule:

    • if curr is less than or equal to prev, add up as usual. Roman numerals can be viewed as a sum of smaller units

    • ...except for 4, 40, 400, etc. where curr is greater than prev, which warrants subtraction of prev from curr

    I came up with a simple algorithm to properly subtract the right amount when 4, 40, 400 occur. This is by no means the one correct answer; there are definitely other ways to go about it. This method was just the clearest for me.

    class Solution {
        public int romanToInt(String s) {
    	  length = s.length();
            int prev = 0;    
            int sum = 0;
            for (int i=0; i<length; i++) {
                int curr = romanMapInt(s.charAt(i));
                if ( curr < prev  ) { 
                    sum += curr;
                }
                else { //4, 40, 400
                    sum += curr;
                    sum -= 2 * prev;
                }
                prev = curr;
            }
        }
    
        public int romanMapInt(char c) {
          int num = 0;
        	switch(c){
            case 'I':
                num = 1;
                break;
            case 'V':
                num = 5;
                break;
             case 'X':
                num = 10;
                break;
             case 'L':
                 num = 50;
                 break;
             case 'C':
                 num = 100;
                 break;
             case 'D':
                 num = 500;
                 break;
             case 'M':
                 num = 1000;
                 break;
             default:
                 num = 0;
                 break;
          }
          return num;
       }  
    }
    

Log in to reply
 

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