DEV Community

Discussion on: Solution: Roman to Integer

Collapse
 
sainiteshb profile image
Sai Nitesh • Edited

Thank you for very detailed explanation.
But i didnt understand why u used 4 in the statement

if(4* num<ans) ans-=num;
Enter fullscreen mode Exit fullscreen mode

can u please explain

Collapse
 
seanpgallivan profile image
seanpgallivan

This part of the explanation covers the 4:

The standard approach would be to use a separate variable to keep track of the highest value seen, but there's an easier trick here. Since numbers generally increase in a roman numeral notation from right to left, any subtractive number must also be smaller than our current ans.

So we can avoid the need for an extra variable here. We do run into the case of repeated numerals causing an issue (ie, "III"), but we can clear that by multiplying num by any number between 2 and 4 before comparing it to ans, since the numerals jump in value by increments of at least 5x.

Collapse
 
sainiteshb profile image
Sai Nitesh

Thank you so much, i got it cleared :)

Collapse
 
jake6868 profile image
Jake6868

why is it wrong when I put the test case with roman number :"CMDM"

Thread Thread
 
seanpgallivan profile image
seanpgallivan

Because that's not a valid Roman numeral sequence. Roman numbers are written in descending value order, with the exception for 9s and 4s and their equivalents in orders of magnitude.

At the start, the "CM" would be read as 900, because "C" is 100 and "M" is 1000. But then you have a "D", which would be another 500, so "CMD" would be 1400. But you'd never write it that way instead of "MCD" which is 1000+400 (rather than 900+500).

Then you have another "M", which is another 1000, but then that "M" should go at the beginning.

So assuming that the "CM" is supposed to be 900 (rather than 1100), then this should be written as "MMCD", or 1000+1000+400 (M+M+CD).

Thread Thread
 
jake6868 profile image
Jake6868

what do you mean by "with the exception for 9s and 4s and their equivalents in orders of magnitude." I don't understand the "s" meaning and why "9s" and "4s". Sorry, if you have time can you explain to me.

Thread Thread
 
zx1986 profile image
張旭