LeetCode: romanToInt & intToRoman

DJ Deustch
2 min readMar 9, 2021

--

I didn’t learn Roman Numerals as a kid nor when I grew up. So it’s hard for me. Or rather, the solution is a loop with trivial if conditions reflecting upon the rules for formations of Roman Numerals.

I only like those LeetCode questions with neat solutions in 30 (maybe) lines; otherwise, I would deem it an engineering hack not possible to be addressed in 15 min during an interview.

The “romanToInt” part is relatively easy, and the solution is short enough for me to write.

The idea is to look the string from left to right.

  1. if the char and the next one (if exists) has an “upward” pattern, do the subtraction;
  2. otherwise, just add the value of that char.

For example, if it’s “MCM”, it should be M + CM not MC+ M, even though both MC and CM are valid.

Still, I’m not a big fan of this question. For example, what if the upward pattern covers more than 2 chars, say “IVX”? According to the rule, it’s simply not possible. Am I supposed to know that?

--

--

No responses yet