I am doing the Roman to integer problem, but I don’t get why my code is working. I troubleshooted and for some reason doubles.containsKey(s.substring(i, i + 2)) is evaluating to false every time.
`import java.util.Map;
import java.util.Map;
class Solution {
public int romanToInt(String s) {
int res = 0;
Map<String, Integer> 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);
Map<String, Integer> doubles = new HashMap<>();
map.put("IV", 4);
map.put("IX", 9);
map.put("XL", 40);
map.put("XC", 90);
map.put("CD", 400);
map.put("CM", 900);
for (int i = 0; i < s.length(); i++) {
String c = s.substring(i, i + 1);
if (i != s.length() - 1 && doubles.containsKey(s.substring(i, i + 2))) {
res += doubles.get(s.substring(i, i + 2));
System.out.println(res);
i++;
} else {
res += map.get(c);
}
}
return res;
}
}
New contributor
user25238578 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.