We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I went with a solution based off what makes an invalid roman numeral.
The numerals M, C, X, and I may be consecutive up to three times or not present at all. If they appear four or more times consecutively, the numeral is invalid. e,g, IIII is an invalid numeral.
The numerals D, L, and V may not appear consecutively or not appear at all. If they appear consecutively at all, the numeral is invalid. e.g. DD is an invalid numeral.
My regex was (?!.*([MCXI])\1{3,})(?!.*([DLV])\2)[IVXLCMD]*.
?! is a negative lookahead: "if the following pattern does not exist, then match".
The pattern is .*([MCXI])\1{3,}: if at any point in the string (.*) we see M, C, X, or I ([MCXI]) consecutively more than four times (\1{3,}), we don't match. If we don't see this pattern, we do match.
The same logic is applied for D, L, and V.
What follows after simply matches any amount of characters that use roman numerals.
This works because HackerRank failed to create a test case such as IIIXVI, which is an incorrect representation of XIX.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Validating Roman Numerals
You are viewing a single comment's thread. Return to all comments →
I went with a solution based off what makes an invalid roman numeral. The numerals M, C, X, and I may be consecutive up to three times or not present at all. If they appear four or more times consecutively, the numeral is invalid. e,g, IIII is an invalid numeral. The numerals D, L, and V may not appear consecutively or not appear at all. If they appear consecutively at all, the numeral is invalid. e.g. DD is an invalid numeral.
My regex was
(?!.*([MCXI])\1{3,})(?!.*([DLV])\2)[IVXLCMD]*
.?!
is a negative lookahead: "if the following pattern does not exist, then match". The pattern is.*([MCXI])\1{3,}
: if at any point in the string (.*
) we see M, C, X, or I ([MCXI]
) consecutively more than four times (\1{3,}
), we don't match. If we don't see this pattern, we do match. The same logic is applied for D, L, and V. What follows after simply matches any amount of characters that use roman numerals.This works because HackerRank failed to create a test case such as
IIIXVI
, which is an incorrect representation ofXIX
.