About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Convert Number To Roman Numeral Problem

Convert Number To Roman Numeral

Given a number, return its equivalent roman numeral.

Example One

Input: 5

Output: V

Example Two

Input: 9

Output: IX

Example Three

Input: 48

Output: XLVIII


Notes

● You can find integer to roman conversion rules here.

● Roman numerals are written as largest to smallest from left to right. Example: 12 is written as 10 + 2 hence roman numeral for 12 is X + II = XII. 

● Some specific cases follow the subtraction rule instead of addition rule. Example: 4 is written as IV instead of IIII. Here, IV denotes 1 less than 5. Some more cases are:

○ 9 is written as IX.

○ 40 is written as XL and 90 as XC.

○ 400 is written as CD and 900 as CM.

Constraints:

● 1


Solution

We provided one solution which is the most intuitive and optimised approach. 

1) simple_solution.cpp

This problem is an implementation problem. We can divide the given number on the basis of place value. For example: 

1942 = 1000 + 900 + 40 + 2 because roman numerals are usually written largest to smallest from left to right. Now, roman numeral for 1942 will be roman numeral of all place values concatenated.

1000 -> M, 900 -> CM, 40 -> XL, 2 -> II

Hence, roman for 1942 will be “MCMXLII”.

We use string arrays to map the place values of (thousands, hundreds, tens, units) to the corresponding roman numeral.

Time Complexity:

O(1).

Auxiliary Space Used:

O(1).

Space Complexity:

O(1).


// -------- START --------

string integer_to_roman(int num) {
    string thousands[] = {"", "M", "MM", "MMM"};
    string hundreds[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    string tens[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    string units[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};

    string roman = "";
    roman += thousands[num / 1000];
    roman += hundreds[(num % 1000) / 100];
    roman += tens[(num % 100) / 10];
    roman += units[num % 10];
    return roman;
}

// -------- END --------


Attend our Free Webinar on How to Nail Your Next Technical Interview

Recommended Posts

All Posts