July 21, 2019

13. Roman to Integer

13. Roman to Integer

Cases:
I V X L C D M
1 5 10 50 100 500 1000

Special cases:
IV IX XL XC CD CM
1 4 40 90 400 900

class Solution {
    public int romanToInt(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int res = 0;
        if (s.indexOf("CM") != -1) res -= 200;
        if (s.indexOf("CD") != -1) res -= 200;
        if (s.indexOf("XC") != -1) res -= 20;
        if (s.indexOf("XL") != -1) res -= 20;
        if (s.indexOf("IX") != -1) res -= 2;
        if (s.indexOf("IV") != -1) res -= 2;
        for (char c : s.toCharArray()) {
            if (c == 'M') res += 1000;
            else if (c == 'D') res += 500;
            else if (c == 'C') res += 100;
            else if (c == 'L') res += 50;
            else if (c == 'X') res += 10;
            else if (c == 'V') res += 5;
            else if (c == 'I') res += 1;
        }
        return res;
    }
}
comments powered by Disqus