Sunday, February 24, 2013

[LeetCode] Roman To Integer


Thought:
From the LSB to the MSB, if current bit's value is smaller than previous bit's value, we should minus this bit, otherwise add this bit.

Code:
public class Solution {
    public int romanToInt(String s) {
       
        HashMap<Character, Integer> roman = new HashMap<Character, Integer>();
       
        roman.put('I', 1);
        roman.put('V', 5);
        roman.put('X', 10);
        roman.put('L', 50);
        roman.put('C', 100);
        roman.put('D', 500);
        roman.put('M', 1000);
       
        int i = s.length() - 1;
        int result = roman.get(s.charAt(i));
        char current = ' ', previous = ' ';
       
        while(i > 0){
            previous = s.charAt(i);
            current = s.charAt(i - 1);
            if(roman.get(current) < roman.get(previous)){
                result = result - roman.get(current);
            }else{
                result = result + roman.get(current);
            }
            i--;
        }       
        return result;       
    }
}

No comments:

Post a Comment