See the original problem on HackerRank.
Given a decimal number N between 1 and 4999, find its corresponding Roman numeral.
Roman numerals are formed by the combination of these letters:
|
|
Rules to combine letters:
- A letter repeats its value that many times (XXX = 30, CC = 200, etc.). A letter can only be repeated three times (except M).
- If one or more letters are placed after another letter of greater value, add that amount (VI = 6 (5+1)).
- If a letter is placed before another letter of greater value, subtract that amount (IV = 4(5-1)).
Input Format
The only input is N.
Constraints
|
|
Output Format
The corresponding roman number.
Solutions
This is a classical problem admitting several solutions.
A solution in Haskell by Massimo Zanibon:
|
|
A Rust solution by Alessandro Pezzato
|
|
A C++ solution based on binary search:
|
|
A more complex solution, in Rust, that uses only single characters instead of already composed numbers in the table.
|
|
A couple of solutions in python by Matteo Italia and Giulia Crotti.
The first uses a lookup on all the available patterns:
|
|
The second defines all the patterns using indexes:
|
|