Convert Integer to Roman Numerals: A Step-by-Step Guide
Written on
Understanding Roman Numerals
To create a program that transforms an integer into a Roman numeral, it is essential to grasp the structure and rules governing Roman numeral representation.
Roman numerals utilize seven distinct symbols:
- I (1)
- V (5)
- X (10)
- L (50)
- C (100)
- D (500)
- M (1000)
These symbols adhere to specific conventions. For instance:
- 1 is denoted as I
- 2 is represented as II
- 3 as III
However, the number 4 is not denoted as IIII. Instead, it utilizes the principle of subtraction, where one is subtracted from five, thus making it IV. This subtractive notation applies to other numbers as well; for example, I precedes V and X, X precedes L and C, and C precedes D and M.
Now that we comprehend the foundational principles, we can proceed to implement the solution in JavaScript.
Defining the Program Structure
Following the principles outlined, we will initiate our program by defining arrays that store the unique combinations of values and their corresponding Roman numeral symbols:
const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const romans = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
The program will accept an integer as input and will compare this value against the array of values to determine its range, such as between 1 to 4, or 100 to 400, etc.
As we identify the range, we will accumulate the result in a string variable called result using a while loop:
let result = "";
for (let i = 0; num > 0; i++) {
while (num >= values[i]) {
result += romans[i];
num -= values[i];
}
}
For instance, if the input is 445, which falls between 400 and 500, we can break it down as follows: 445 = 400 + 45. Therefore, the result will be:
result = "CD" + "XL" + "V"; // CDXLV
Consequently, our final output will be CDXLV.
Complete JavaScript Solution
Here is the full implementation of the solution:
const intToRoman = function(num) {
let result = "";
for (let i = 0; num > 0; i++) {
while (num >= values[i]) {
result += romans[i];
num -= values[i];
}
}
return result;
};
Conclusion
I hope you found this guide helpful! If you have alternative solutions or insights on this problem, feel free to share. This programming challenge is considered of medium difficulty and serves as excellent preparation for technical interviews. You can also practice this problem on LeetCode.
In my next article, we will develop a Roman numeral calculator.
This video demonstrates how to convert a given integer into Roman numerals, guiding you through the implementation process.
In this video, learn how to convert any number to a Roman numeral, offering additional insights and examples.