Tuesday, February 11, 2014

Roman to Integer

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution:
Do we need the background knowledge? Or should it be given in the question?
public class Solution {
    public int romanToInt(String s) {
        int sum = 0;
        int i = 0;
        while(i < s.length()){
            int temp = 0;
            char c = s.charAt(i);
            char cc;
            if (i != s.length()-1) {
                cc = s.charAt(i+1);
                if(isSubNotation(c,cc)){
                    temp = convertLetter(cc) - convertLetter(c);
                    i++;
                }
                else{
                    temp = convertLetter(c);
                }
            }
            else{
                temp = convertLetter(c);
            }
            sum = sum + temp;
            i++;
        }
        return sum;
    }
    public Boolean isSubNotation(char first, char second){
        if(first == 'I'){
            if((second == 'V') || (second == 'X')) return true;
        }
        if(first == 'X'){
            if((second == 'L') || (second == 'C')) return true;
        }
        if(first == 'C'){
            if((second == 'D') || (second == 'M')) return true;
        }
        return false;
    }
    public int convertLetter(char c){
        int temp = 0;;
        switch (c) {
                case 'I': temp = 1;
                          break;
                case 'V': temp = 5;
                          break;
                case 'X': temp = 10;
                          break;
                case 'L': temp = 50;
                          break;
                case 'C': temp = 100;
                          break;
                case 'D': temp = 500;
                          break;
                case 'M': temp = 1000;
                          break;
        }
        return temp;
    }
}

No comments:

Post a Comment