I was on the LeetCode website earlier today, more often than not the problems on this site scare the living hell out of me, however one caught my eye and I naively thought “that can’t be that hard can it?”, you’d think by now I’d know better than that, but the problem felt solvable and interesting enough for me to have a bash at it.
The idea is to have a function to convert numbers to roman numerals.
Must be simple right? – that’s what I thought originally, then I started to remember how roman numerals work.
How do Roman Numerals Work?
There are 7 different symbols used in the Roman Numeral System;
Roman Symbol | Value |
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
All of this seems fine – a simple translation function, right? Well… not entirely There are some exceptions for example.
- The Number 4 isn’t IIII it is IV (one before 5)
- The Number 40 is XL (10 before 50)
My knowledge of these exceptions isn’t complete however a quick google search told me there are 6 instances where subtraction is used;
- 4 and 9 are IV and IX
- 40 and 90 are XL and XC
- 400 and 900 are CD and CM
Knowing this a good starting point would be to make a dictionary (hashmap) object that contains these symbols and their values (basically an extension of the table above);
Key | Value |
I | 1 |
IV | 4 |
V | 5 |
IX | 9 |
X | 10 |
XL | 40 |
L | 50 |
XC | 90 |
C | 100 |
CD | 400 |
D | 500 |
CM | 900 |
M | 1000 |
Now I have a table I can use to translate the numbers to the symbols I need to consider the method in which this would work.
Conversion Approach
One way of doing this conversion is via subtraction – you want to remove the largest value possible from the original number and leave the remainder for future subtractions.
Let’s take for example the Number 475
Step One
if we were to loop through the dictionary in descending order the symbol <=475 would be CD (400) leaving us with 75 left to resolve.
Step Two
The smallest number <=75 is L (50) leaving us with 25
Step Three
The smallest number <=25 is X (10) leaving us with 15
Step Four
The smallest Number <= 15 is X (10) leaving us with 5
Step Five
The smallest number <=5 is V (5) leaving us with 0
Therefore, the Roman Numeral for 475 is CDLXXV
Once you realise this the code is fairly simple. Keep looping and subtracting until your resulting value is equal to 0. This is not necessarily an exercise in coding, but more problem solving.
To show this works lets pass the number 2022 to the program- the output given is.
which is correct as 2022 = 1000 (M) + 1000 (M) + 10 (X) + 10 (X) + 1 (I) + 1 (I)
Example Code is at:ConvertNumberToRomanNumeral(github.com)
A useful website on roman numerals (should you ever need to look at this?!) is Rules for Formation of Roman Numerals