package com.zerroi.leetcode.Three11; import java.util.HashMap; import java.util.Map; public class RomanToInt { public static void main(String[] args) { SolutionFirst solutionFirst = new SolutionFirst(); int res = solutionFirst.romanToInt("XLVI"); System.out.println("res = " + res); } } class SolutionFirst { public int romanToInt(String s) { Map map = new HashMap<>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); int res = 0; for (int i = 0; i < s.length(); i++) { if (i != s.length() - 1) { if (map.get(s.charAt(i + 1)) > map.get(s.charAt(i))) { res += map.get(s.charAt(i + 1)) - map.get(s.charAt(i)); i++; } else { res += map.get(s.charAt(i)); } } else { res += map.get(s.charAt(i)); } } return res; } }