re: Roman Numeral Converter VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION
 

The way it works is by subtracting until you can add based only on the one-to-one mapping in descending order. So if you're trying to convert 1990, it goes like this:

  1. 1990, evaluate M (1000); 1990 > 1000 so we have an M, leaving 990 for the next iteration
  2. 990 is less than 1000 so MM is wrong, but it's more than 900 (1000 - (1000 / 10)), so we set the lastEntry pointer to M and proceed
  3. Now we're evaluating C (100), but lastEntry is set. 990 > 900 which is CM, giving us MCM so far and leaving 90. I think this is where the bug is but it works in this case :)
  4. 90 > (100 - (100 / 10)) so lastEntry is now C
  5. Evaluate L (50); lastEntry is set, but the calculation to test whether L can be subtracted fails, so we proceed
  6. Evaluate X (10): the subtraction test succeeds, so 90 becomes XC and the full result is MCMXC.

Nice that’s such a cool way of thinking about it!

code of conduct - report abuse