Home

13. Roman To Integer

Detailed explanation coming soon!

/*
 * Read string backwards
 */

class Solution {

  int[] romanMap;

  public Solution() {
    romanMap = new int[128];
    romanMap[(int)'I'] = 1;
    romanMap[(int)'V'] = 5;
    romanMap[(int)'X'] = 10;
    romanMap[(int)'L'] = 50;
    romanMap[(int)'C'] = 100;
    romanMap[(int)'D'] = 500;
    romanMap[(int)'M'] = 1000;
  }

  public int romanToInt(String s) {
    if (s == null || s.length() < 1) return 0;

    char lastChar = s.charAt(s.length() - 1);
    int amount = romanMap[(int)lastChar];

    for (int i = s.length() - 2; i >= 0; i--) {
      char c = s.charAt(i);

      if (isLessThan(c, lastChar)) {
        amount -= romanMap[(int)c];
      } else {
        amount += romanMap[(int)c];
      }

      lastChar = c;
    }

    return amount;
  }

  // Returns true if roman numeral `a` is smaller than roman numeral `b`
  public boolean isLessThan(char a, char b) {
    return romanMap[(int)a] < romanMap[(int)b];
  }
}


Questions? Have a neat solution? Comment below!