Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIConverting Decimal Number lying between 1 to 3999 to Roman Numerals

Converting Decimal Number lying between 1 to 3999 to Roman Numerals

Given a number, find its corresponding Roman numeral. 

Examples: 

Input : 9
Output : IX
Input : 40
Output : XL
Input : 1904
Output : MCMIV

Following is the list of Roman symbols which include subtractive cases also:

SYMBOL       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
Recommended Practice

Idea is to convert the units, tens, hundreds, and thousands of places of the given number separately. If the digit is 0, then there’s no corresponding Roman numeral symbol. The conversion of digit’s 4’s and 9’s are little bit different from other digits because these digits follow subtractive notation

Algorithm to convert decimal number to Roman Numeral 
Compare given number with base values in the order 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1. Base value which is just smaller or equal to the given number will be the initial base value (largest base value) .Divide the number by its largest base value, the corresponding base symbol will be repeated quotient times, the remainder will then become the number for future division and repetitions.The process will be repeated until the number becomes zero.

Example to demonstrate above algorithm: 

Convert 3549 to its Roman Numerals

Output: 

MMMDXLIX

Explanation: 

Explanation:

Step 1

  • Initially number = 3549
  • Since 3549 >= 1000 ; largest base value will be 1000 initially.
  • Divide 3549/1000. Quotient = 3, Remainder =549. The corresponding symbol M will be repeated thrice.
  • We append the Result value in the 2nd List.
  • Now Remainder is not equal to 0 so we call the function again.

Step 2

  • Now, number = 549
  • 1000 > 549 >= 500 ; largest base value will be 500.
  • Divide 549/500. Quotient = 1, Remainder =49. The corresponding symbol D will be repeated once & stop the loop.
  • We append the Result value in the 2nd List.
  • Now Remainder is not equal to 0 so we call the function again.

Step 3

  • Now, number = 49
  • 50 > 49 >= 40 ; largest base value is 40.
  • Divide 49/40. Quotient = 1, Remainder = 9. The corresponding symbol XL will be repeated once & stop the loop.
  • We append the Result value in the 2nd List.
  • Now Remainder is not equal to 0 so we call the function again.

Step 4

  • Now, number = 9
  • Number 9 is present in list ls so we directly fetch the value from dictionary dict and set Remainder=0 & stop the loop.
  • Remainder = 0. The corresponding symbol IX will be repeated once and now remainder value is 0 so we will not call the function again.

Step 5

  • Finally, we join the 2nd list values.
  • The output obtained MMMDXLIX.

Following is the implementation of the above algorithm: 

C++




// C++ Program to convert decimal number to
// roman numerals
#include <bits/stdc++.h>
using namespace std;
 
// Function to convert decimal to Roman Numerals
int printRoman(int number)
{
    int num[] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
    string sym[] = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
    int i=12;   
    while(number>0)
    {
      int div = number/num[i];
      number = number%num[i];
      while(div--)
      {
        cout<<sym[i];
      }
      i--;
    }
}
 
//Driver program
int main()
{
    int number = 3549;
 
    printRoman(number);
 
    return 0;
}


Java




// Java Program to convert decimal number to
// roman numerals
class GFG {
 
// To add corresponding base symbols in the array
// to handle cases that follow subtractive notation.
// Base symbols are added index 'i'.
    static int sub_digit(char num1, char num2, int i, char[] c) {
        c[i++] = num1;
        c[i++] = num2;
        return i;
    }
 
// To add symbol 'ch' n times after index i in c[]
    static int digit(char ch, int n, int i, char[] c) {
        for (int j = 0; j < n; j++) {
            c[i++] = ch;
        }
        return i;
    }
 
// Function to convert decimal to Roman Numerals
    static void printRoman(int number) {
        char c[] = new char[10001];
        int i = 0;
 
        // If number entered is not valid
        if (number <= 0) {
            System.out.printf("Invalid number");
            return;
        }
 
        // TO convert decimal number to roman numerals
        while (number != 0) {
            // If base value of number is greater than 1000
            if (number >= 1000) {
                // Add 'M' number/1000 times after index i
                i = digit('M', number / 1000, i, c);
                number = number % 1000;
            } // If base value of number is greater than or
            // equal to 500
            else if (number >= 500) {
                // To add base symbol to the character array
                if (number < 900) {
                    // Add 'D' number/1000 times after index i
                    i = digit('D', number / 500, i, c);
                    number = number % 500;
                } // To handle subtractive notation in case of number
                // having digit as 9 and adding corresponding base
                // symbol
                else {
                    // Add C and M after index i/.
                    i = sub_digit('C', 'M', i, c);
                    number = number % 100;
                }
            } // If base value of number is greater than or equal to 100
            else if (number >= 100) {
                // To add base symbol to the character array
                if (number < 400) {
                    i = digit('C', number / 100, i, c);
                    number = number % 100;
                } // To handle subtractive notation in case of number
                // having digit as 4 and adding corresponding base
                // symbol
                else {
                    i = sub_digit('C', 'D', i, c);
                    number = number % 100;
                }
            } // If base value of number is greater than or equal to 50
            else if (number >= 50) {
                // To add base symbol to the character array
                if (number < 90) {
                    i = digit('L', number / 50, i, c);
                    number = number % 50;
                } // To handle subtractive notation in case of number
                // having digit as 9 and adding corresponding base
                // symbol
                else {
                    i = sub_digit('X', 'C', i, c);
                    number = number % 10;
                }
            } // If base value of number is greater than or equal to 10
            else if (number >= 10) {
                // To add base symbol to the character array
                if (number < 40) {
                    i = digit('X', number / 10, i, c);
                    number = number % 10;
                } // To handle subtractive notation in case of
                // number having digit as 4 and adding
                // corresponding base symbol
                else {
                    i = sub_digit('X', 'L', i, c);
                    number = number % 10;
                }
            } // If base value of number is greater than or equal to 5
            else if (number >= 5) {
                if (number < 9) {
                    i = digit('V', number / 5, i, c);
                    number = number % 5;
                } // To handle subtractive notation in case of number
                // having digit as 9 and adding corresponding base
                // symbol
                else {
                    i = sub_digit('I', 'X', i, c);
                    number = 0;
                }
            } // If base value of number is greater than or equal to 1
            else if (number >= 1) {
                if (number < 4) {
                    i = digit('I', number, i, c);
                    number = 0;
                } // To handle subtractive notation in case of
                // number having digit as 4 and adding corresponding
                // base symbol
                else {
                    i = sub_digit('I', 'V', i, c);
                    number = 0;
                }
            }
        }
 
        // Printing equivalent Roman Numeral
        System.out.printf("Roman numeral is: ");
        for (int j = 0; j < i; j++) {
            System.out.printf("%c", c[j]);
        }
    }
 
//Driver program
    public static void main(String[] args) {
        int number = 3549;
 
        printRoman(number);
    }
}
// This code is contributed by PrinciRaj1992


Python3




# Python3 program to convert
# decimal number to roman numerals
 
ls=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
dict={1:"I",4:"IV",5:"V",9:"IX",10:"X",40:"XL",50:"L",90:"XC",100:"C",400:"CD",500:"D",900:"CM",1000:"M"}
ls2=[]
 
# Function to convert decimal to Roman Numerals
def func(no,res):
    for i in range(0,len(ls)):
        if no in ls:
            res=dict[no]
            rem=0
            break
        if ls[i]<no:
            quo=no//ls[i]
            rem=no%ls[i]
            res=res+dict[ls[i]]*quo
            break
    ls2.append(res)
    if rem==0:
        pass
    else:
        func(rem,"")
 
 
# Driver code
if __name__ == "__main__":
    func(3549, "")
    print("".join(ls2))
 
# This code is contributed by
# VIKAS CHOUDHARY(vikaschoudhary344)


C#




// C# Program to convert decimal number
// to roman numerals
using System;
class GFG
{
 
// To add corresponding base symbols in the
// array to handle cases which follow subtractive
// notation. Base symbols are added index 'i'.
static int sub_digit(char num1, char num2,
                         int i, char[] c)
{
    c[i++] = num1;
    c[i++] = num2;
    return i;
}
 
// To add symbol 'ch' n times after index i in c[]
static int digit(char ch, int n, int i, char[] c)
{
    for (int j = 0; j < n; j++)
    {
        c[i++] = ch;
    }
    return i;
}
 
// Function to convert decimal to Roman Numerals
static void printRoman(int number)
{
    char[] c = new char[10001];
    int i = 0;
 
    // If number entered is not valid
    if (number <= 0)
    {
        Console.WriteLine("Invalid number");
        return;
    }
 
    // TO convert decimal number to
    // roman numerals
    while (number != 0)
    {
        // If base value of number is
        // greater than 1000
        if (number >= 1000)
        {
            // Add 'M' number/1000 times after index i
            i = digit('M', number / 1000, i, c);
            number = number % 1000;
        }
         
        // If base value of number is greater
        // than or equal to 500
        else if (number >= 500)
        {
            // To add base symbol to the character array
            if (number < 900)
            {
                 
                // Add 'D' number/1000 times after index i
                i = digit('D', number / 500, i, c);
                number = number % 500;
            }
             
            // To handle subtractive notation in case
            // of number having digit as 9 and adding
            // corresponding base symbol
            else
            {
                 
                // Add C and M after index i/.
                i = sub_digit('C', 'M', i, c);
                number = number % 100;
            }
        }
         
        // If base value of number is greater
        // than or equal to 100
        else if (number >= 100)
        {
            // To add base symbol to the character array
            if (number < 400)
            {
                i = digit('C', number / 100, i, c);
                number = number % 100;
            }
             
            // To handle subtractive notation in case
            // of number having digit as 4 and adding
            // corresponding base symbol
            else
            {
                i = sub_digit('C', 'D', i, c);
                number = number % 100;
            }
        }
         
        // If base value of number is greater
        // than or equal to 50
        else if (number >= 50)
        {
             
            // To add base symbol to the character array
            if (number < 90)
            {
                i = digit('L', number / 50, i, c);
                number = number % 50;
            }
             
            // To handle subtractive notation in case
            // of number having digit as 9 and adding
            // corresponding base symbol
            else
            {
                i = sub_digit('X', 'C', i, c);
                number = number % 10;
            }
        }
         
        // If base value of number is greater
        // than or equal to 10
        else if (number >= 10)
        {
             
            // To add base symbol to the character array
            if (number < 40)
            {
                i = digit('X', number / 10, i, c);
                number = number % 10;
            }
             
            // To handle subtractive notation in case of
            // number having digit as 4 and adding
            // corresponding base symbol
            else
            {
                i = sub_digit('X', 'L', i, c);
                number = number % 10;
            }
        }
         
        // If base value of number is greater
        // than or equal to 5
        else if (number >= 5)
        {
            if (number < 9)
            {
                i = digit('V', number / 5, i, c);
                number = number % 5;
            }
             
            // To handle subtractive notation in case
            // of number having digit as 9 and adding
            // corresponding base symbol
            else
            {
                i = sub_digit('I', 'X', i, c);
                number = 0;
            }
        }
         
        // If base value of number is greater
        // than or equal to 1
        else if (number >= 1)
        {
            if (number < 4)
            {
                i = digit('I', number, i, c);
                number = 0;
            }
             
            // To handle subtractive notation in
            // case of number having digit as 4
            // and adding corresponding base symbol
            else
            {
                i = sub_digit('I', 'V', i, c);
                number = 0;
            }
        }
    }
 
    // Printing equivalent Roman Numeral
    Console.WriteLine("Roman numeral is: ");
    for (int j = 0; j < i; j++)
    {
        Console.Write("{0}", c[j]);
    }
}
 
// Driver Code
public static void Main()
{
    int number = 3549;
 
    printRoman(number);
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// JavaScript Program to convert decimal number to
// roman numerals
 
 
// Function to convert decimal to Roman Numerals
function printRoman(number)
{
    let num = [1,4,5,9,10,40,50,90,100,400,500,900,1000];
    let sym = ["I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"];
    let i=12;
    while(number>0)
    {
    let div = Math.floor(number/num[i]);
    number = number%num[i];
    while(div--)
    {
        document.write(sym[i]);
    }
    i--;
    }
}
 
//Driver program
 
    let number = 3549;
 
    printRoman(number);
 
//This code is contributed by Manoj
</script>


Output

MMMDXLIX




Time Complexity: O(N), where N is the length of ans string that stores the conversion.
Auxiliary Space: O(N)

References : http://blog.functionalfun.net/2009/01/project-euler-89-converting-to-and-from.html

Another Approach 1:
In this approach, we have to first observe the problem. The number given in problem statement can be maximum of 4 digits. The idea to solve this problem is: 

  1. Divide the given number into digits at different places like one’s, two’s, hundred’s or thousand’s.
  2. Starting from the thousand’s place print the corresponding roman value. For example, if the digit at thousand’s place is 3 then print the roman equivalent of 3000.
  3. Repeat the second step until we reach one’s place.

Example
Suppose the input number is 3549. So, starting from thousand’s place we will start printing the roman equivalent. In this case we will print in the order as given below: 
First: Roman equivalent of 3000 
Second: Roman equivalent of 500 
Third: Roman equivalent of 40 
Fourth: Roman equivalent of 9 
So, the output will be: MMMDXLIX

Below is the implementation of above idea. 

C++




// C++ Program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate roman equivalent
string intToRoman(int num)
{
    // storing roman values of digits from 0-9
    // when placed at different places
    string m[] = { "", "M", "MM", "MMM" };
    string c[] = { """C""CC""CCC""CD",
                   "D", "DC", "DCC", "DCCC", "CM" };
    string x[] = { """X""XX""XXX""XL",
                   "L", "LX", "LXX", "LXXX", "XC" };
    string i[] = { """I""II""III""IV",
                   "V", "VI", "VII", "VIII", "IX" };
 
    // Converting to roman
    string thousands = m[num / 1000];
    string hundreds = c[(num % 1000) / 100];
    string tens = x[(num % 100) / 10];
    string ones = i[num % 10];
 
    string ans = thousands + hundreds + tens + ones;
 
    return ans;
}
 
// Driver program to test above function
int main()
{
    int number = 3549;
    cout << intToRoman(number);
    return 0;
}


Java




// Java Program for above approach
 
class GFG {
    // Function to calculate roman equivalent
    static String intToRoman(int num)
    {
        // storing roman values of digits from 0-9
        // when placed at different places
        String m[] = { "", "M", "MM", "MMM" };
        String c[] = { """C""CC""CCC""CD",
                       "D", "DC", "DCC", "DCCC", "CM" };
        String x[] = { """X""XX""XXX""XL",
                       "L", "LX", "LXX", "LXXX", "XC" };
        String i[] = { """I""II""III""IV",
                       "V", "VI", "VII", "VIII", "IX" };
 
        // Converting to roman
        String thousands = m[num / 1000];
        String hundreds = c[(num % 1000) / 100];
        String tens = x[(num % 100) / 10];
        String ones = i[num % 10];
 
        String ans = thousands + hundreds + tens + ones;
 
        return ans;
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
        int number = 3549;
        System.out.println(intToRoman(number));
    }
}


Python3




# Python3 program for above approach
 
# Function to calculate roman equivalent
 
 
def intToRoman(num):
 
    # Storing roman values of digits from 0-9
    # when placed at different places
    m = ["", "M", "MM", "MMM"]
    c = ["", "C", "CC", "CCC", "CD", "D",
         "DC", "DCC", "DCCC", "CM "]
    x = ["", "X", "XX", "XXX", "XL", "L",
         "LX", "LXX", "LXXX", "XC"]
    i = ["", "I", "II", "III", "IV", "V",
         "VI", "VII", "VIII", "IX"]
 
    # Converting to roman
    thousands = m[num // 1000]
    hundreds = c[(num % 1000) // 100]
    tens = x[(num % 100) // 10]
    ones = i[num % 10]
 
    ans = (thousands + hundreds +
           tens + ones)
 
    return ans
 
 
# Driver code
if __name__ == "__main__":
 
    number = 3549
 
    print(intToRoman(number))
 
# This code is contributed by rutvik_56


C#




// C# Program for above approach
 
using System;
class GFG {
    // Function to calculate roman equivalent
    static String intToRoman(int num)
    {
        // storing roman values of digits from 0-9
        // when placed at different places
        String[] m = { "", "M", "MM", "MMM" };
        String[] c = { """C""CC""CCC""CD",
                       "D", "DC", "DCC", "DCCC", "CM" };
        String[] x = { """X""XX""XXX""XL",
                       "L", "LX", "LXX", "LXXX", "XC" };
        String[] i = { """I""II""III""IV",
                       "V", "VI", "VII", "VIII", "IX" };
 
        // Converting to roman
        String thousands = m[num / 1000];
        String hundreds = c[(num % 1000) / 100];
        String tens = x[(num % 100) / 10];
        String ones = i[num % 10];
 
        String ans = thousands + hundreds + tens + ones;
 
        return ans;
    }
 
    // Driver program to test above function
    public static void Main()
    {
        int number = 3549;
        Console.WriteLine(intToRoman(number));
    }
}


Javascript




<script>
 
// JavaScript Program for above approach
 
// Function to calculate roman equivalent
function intToRoman(num)
{
    // storing roman values of digits from 0-9
    // when placed at different places
    let m = ["", "M", "MM", "MMM"];
    let c = ["", "C", "CC", "CCC", "CD", "D",
                        "DC", "DCC", "DCCC", "CM"];
    let x = ["", "X", "XX", "XXX", "XL", "L",
                        "LX", "LXX", "LXXX", "XC"];
    let i = ["", "I", "II", "III", "IV", "V",
                        "VI", "VII", "VIII", "IX"];
         
    // Converting to roman
    let a1 = Math.floor(num/1000);
    let a2 = Math.floor((num%1000)/100);
    let a3 = Math.floor((num%100)/10);
 
    let thousands = m[a1];
    let hundreds = c[a2];
    let tens = x[a3];
    let ones = i[num%10];
         
    let ans = thousands + hundreds + tens + ones;
         
    return ans;
}
 
// Driver program to test above function
 
    let number = 3549;
    document.write(intToRoman(number));
     
 
//This code is contributed by Mayank Tyagi
</script>


PHP




<?php
// PHP Program for above approach
 
// Function to calculate roman equivalent
function intToRoman($num)
{
    // storing roman values of digits from 0-9
    // when placed at different places
    $m = array("", "M", "MM", "MMM");
    $c = array("", "C", "CC", "CCC", "CD", "D",
                   "DC", "DCC", "DCCC", "CM");
    $x = array("", "X", "XX", "XXX", "XL", "L",
                   "LX", "LXX", "LXXX", "XC");
    $i = array("", "I", "II", "III", "IV", "V",
                   "VI", "VII", "VIII", "IX");
         
    // Converting to roman
    $thousands = $m[$num / 1000];
    $hundreds = $c[($num % 1000) / 100];
    $tens = $x[($num % 100) / 10];
    $ones = $i[$num % 10];
         
    $ans = $thousands . $hundreds . $tens . $ones;
         
    return $ans;
}
 
// Driver Code
$number = 3549;
echo intToRoman($number);
 
// This code is contributed by Akanksha Rai


Output

MMMDXLIX




Time Complexity: O(N), where N is the length of ans string that stores the conversion.
Auxiliary Space: O(N)

Thanks to Shashwat Jain for providing the above solution approach.

Another Approach 2:
In this approach we consider the main significant digit in the number. Ex: in 1234, main significant digit is 1. Similarly in 345 it is 3. 
In order to extract main significant digit out, we need to maintain a divisor (lets call it div) like 1000 for 1234 (since 1234 / 1000 = 1) and 100 for 345 (345 / 100 = 3). 
Also, lets maintain a dictionary called romanNumeral = {1 : ‘I’, 5: ‘V’, 10: ‘X’, 50: ‘L’, 100: ‘C’, 500: ‘D’, 1000: ‘M’} 

Following is the algorithm: 

if main significant digit <= 3

  • romanNumeral[div] * mainSignificantDigit 

if main significant digit == 4

  • romanNumeral[div] + romanNumeral[div * 5] 

if 5 <= main significant digit <=8

  • romanNumeral[div * 5] + (romanNumeral[div] * ( mainSignificantDigit-5))

if main significant digit ==9

  • romanNumeral[div] + romanNumeral[div*10]

Example
Suppose the input number is 3649. 

Iter 1
 

  • Initially number = 3649
  • main significant digit is 3. Div = 1000.
  • So, romanNumeral[1000] * 3
  • gives: MMM 

Iter 2

  • now, number = 649
  • main significant digit is 6. Div = 100.
  • So romanNumeral[100*5] + (romanNumeral[div] * ( 6-5))
  • gives: DC 

Iter 3

  • now, number = 49
  • main significant digit is 4. Div = 10.
  • So romanNumeral[10] + romanNumeral[10 * 5]
  • gives: XL

Iter 4

  • now, number = 9
  • main significant digit is 9. Div = 1.
  • So romanNumeral[1] * romanNumeral[1*10]
  • gives: IX

Final result by clubbing all the above: MMMDCXLIX  

Below is the Python implementation of above idea.

C++




#include <bits/stdc++.h>
#include <unordered_map>
 
using namespace std;
 
string integerToRoman(int num) {
  unordered_map<int, char> roman; // move outside
  roman[1] = 'I';
  roman[5] = 'V';
  roman[10] = 'X';
  roman[50] = 'L';
  roman[100] = 'C';
  roman[500] = 'D';
  roman[1000] = 'M';
  roman[5000] = 'G';
  roman[10000] = 'H';
   
  string tmp = to_string(num);
  const int numDigits = tmp.length();
   
  string res = "";
  for(int i=0;i<numDigits;++i) {
    const char src = tmp[i]; // orig
    const int number = (src - '0'); // convert to integer
    const int place = (numDigits-1)-i;
    const int absolute = pow(10, place);
     
    if (number == 9) {
        res.append(1, roman[absolute]);
        res.append(1, roman[(number+1) * absolute]);
    else
    if (number >= 5) {
        res.append(1, roman[5*absolute]);
        res.append(number-5, roman[absolute]);
    else
    if (number >= 4) {
        res.append(1, roman[absolute]);
        res.append(1, roman[5*absolute]);
    } else {
        res.append(number, roman[absolute]);
    }
  }
  return res;
}
 
int main() {
  cout << integerToRoman(3549) << endl;
  return 0;
}
 
// This code is contributed by elviscastillo.


Java




// Java program for above approach
import java.util.*;
 
public class Solution {
  static String integerToRoman(int num)
  {
    HashMap<Integer, Character> roman = new HashMap<>();
    roman.put(1, 'I');
    roman.put(5, 'V');
    roman.put(10, 'X');
    roman.put(50, 'L');
    roman.put(100, 'C');
    roman.put(500, 'D');
    roman.put(1000, 'M');
    roman.put(5000, 'G');
    roman.put(10000, 'H');
 
    String tmp = num + "";
    int numDigits = tmp.length();
 
    String res = "";
    for (int i = 0; i < numDigits; ++i) {
      char src = tmp.charAt(i); // orig
      int number = (src - '0'); // convert to integer
      int place = (numDigits - 1) - i;
      int absolute = (int)Math.pow(10, place);
 
      if (number == 9) {
        res += roman.get(absolute);
        res += roman.get(absolute * 10);
      }
      else if (number >= 5) {
        res += roman.get(absolute * 5);
        res += (roman.get(absolute) + "")
          .repeat(number - 5);
      }
      else if (number == 4) {
        res += roman.get(absolute);
        res += roman.get(absolute * 5);
      }
      else {
        res += (roman.get(absolute) + "")
          .repeat(number);
      }
    }
    return res;
  }
 
  public static void main(String[] args)
  {
    System.out.println("Roman Numeral of Integer is:"
                       + integerToRoman(3549));
  }
}
 
// This code is contributed by karandeep1234.


Python3




# Python 3 program to convert Decimal
# number to Roman numbers.
import math
 
def integerToRoman(A):
    romansDict = \
        {
            1: "I",
            5: "V",
            10: "X",
            50: "L",
            100: "C",
            500: "D",
            1000: "M",
            5000: "G",
            10000: "H"
        }
 
    div = 1
    while A >= div:
        div *= 10
 
    div //= 10
 
    res = ""
 
    while A:
 
        # main significant digit extracted
        # into lastNum
        lastNum = (A // div)
 
        if lastNum <= 3:
            res += (romansDict[div] * lastNum)
        elif lastNum == 4:
            res += (romansDict[div] +
                          romansDict[div * 5])
        elif 5 <= lastNum <= 8:
            res += (romansDict[div * 5] +
            (romansDict[div] * (lastNum - 5)))
        elif lastNum == 9:
            res += (romansDict[div] +
                         romansDict[div * 10])
 
        A = math.floor(A % div)
        div //= 10
         
    return res
 
# Driver code
print("Roman Numeral of Integer is:"
                   + str(integerToRoman(3549)))


C#




// C# program for above approach
using System;
using System.Collections.Generic;
 
public class GFG {
  static String integerToRoman(int num)
  {
    Dictionary<int, char> roman
      = new Dictionary<int, char>();
    roman[1] = 'I';
    roman[5] = 'V';
    roman[10] = 'X';
    roman[50] = 'L';
    roman[100] = 'C';
    roman[500] = 'D';
    roman[1000] = 'M';
    roman[5000] = 'G';
    roman[10000] = 'H';
 
    string tmp = num + "";
    int numDigits = tmp.Length;
 
    String res = "";
    for (int i = 0; i < numDigits; ++i) {
      char src = tmp[i]; // orig
      int number = (src - '0'); // convert to integer
      int place = (numDigits - 1) - i;
      int absolute = (int)Math.Pow(10, place);
 
      if (number == 9) {
        res += roman[absolute];
        res += roman[absolute * 10];
      }
      else if (number >= 5) {
        res += roman[absolute * 5];
        res += new string(roman[absolute],
                          number - 5);
      }
      else if (number == 4) {
        res += roman[absolute];
        res += roman[absolute * 5];
      }
      else {
        res += new string(roman[absolute], number);
      }
    }
    return res;
  }
 
  public static void Main(string[] args)
  {
    Console.WriteLine("Roman Numeral of Integer is:"
                      + integerToRoman(3549));
  }
}
 
// This code is contributed by karandeep1234.


Javascript




// javascript code implementation
 
function integerToRoman(num) {
    let roman = new Map(); // move outside
    roman.set(1, 'I');
    roman.set(5, 'V');
    roman.set(10, 'X');
    roman.set(50, 'L');
    roman.set(100, 'C');
    roman.set(500, 'D');
    roman.set(1000, 'M');
    roman.set(5000, 'G');
    roman.set(10000, 'H');
     
    let tmp = Array.from(String(num));
    let numDigits = tmp.length;
   
    let res = [];
    for(let i=0;i<numDigits;++i) {
        let src = tmp[i]; // orig
        let number = (src.charCodeAt(0) - 48); // convert to integer
        let place = (numDigits-1)-i;
        let absolute = Math.pow(10, place);
 
        if (number == 9) {
            res.push(roman.get(absolute));
            res.push(roman.get((number+1) * absolute));
        else
        if (number >= 5) {
            res.push(roman.get(5*absolute));
             
            let cnt = number-5;
            while(cnt--) res.push(roman.get(absolute));
        
        else{
            if (number >= 4) {
                res.push(roman.get(absolute));
                res.push(roman.get(5*absolute));
            }
            else {
                 
                let cnt = number;
                while(cnt--) res.push(roman.get(absolute));
            }
        }
    }
    return res;
}
 
let ans = integerToRoman(3549).join('');
console.log(ans);
 
// This code is contributed by Nidhi goel.


Output

Roman Numeral of Integer is:MMMDXLIX




Time Complexity: O(N), where N is the length of res string that stores the conversion.
Auxiliary Space: O(N)

Thanks to Sriharsha Sammeta for providing the above solution approach.

Approach 3: Using Ladder if-else

The idea is simple, it follows the basic fundamentals of roman numbers as iterating through the greatest to smallest number using if else and check of it exist then add that roman symbol to the answer and decrement that number.

Steps to solve the problem:

  • Declare ans variable to store the roman symbol.
  • Iterate through all the roman integer value from greatest to smallest until the number is not equal to zero:
    • If num>=1000 then ans+=”M” and num-=1000.
    • else if num>=900 && num<1000 then ans+=”CM” and num-=900, and so on till num is not zero
  • 4. Return the ans

Implementation of the approach:

C++




// C++ Program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate roman equivalent
string intToRoman(int num)
{
  //Initialize the ans string
    string ans = "";
  //calculate the roman numbers
    while (num) {
        if (num >= 1000) {
            ans += "M";
            num -= 1000;
        }
      //check for all the corner cases like 900,400,90,40,9,4 etc.
        else if (num >= 900 && num < 1000) {
            ans += "CM";
            num -= 900;
        }
        else if (num >= 500 && num < 900) {
            ans += "D";
            num -= 500;
        }
        else if (num >= 400 && num < 500) {
            ans += "CD";
            num -= 400;
        }
        else if (num >= 100 && num < 400) {
            ans += "C";
            num -= 100;
        }
        else if (num >= 90 && num < 100) {
            ans += "XC";
            num -= 90;
        }
        else if (num >= 50 && num < 90) {
            ans += "L";
            num -= 50;
        }
        else if (num >= 40 && num < 50) {
            ans += "XL";
            num -= 40;
        }
        else if (num >= 10 && num < 40) {
            ans += "X";
            num -= 10;
        }
        else if (num == 9) {
            ans += "IX";
            num -= 9;
        }
        else if (num >= 5 && num < 9) {
            ans += "V";
            num -= 5;
        }
        else if (num == 4) {
            ans += "IV";
            num -= 4;
        }
        else if (num < 4) {
            ans += "I";
            num--;
        }
    }
  //return the result
    return ans;
}
 
// Driver program to test above function
int main()
{
    int number = 3549;
    cout << intToRoman(number);
    return 0;
}
//This code is contributed by Prateek Kumar Singh


Java




// Java program for the above approach
import java.util.*;
  
public class Solution {
  static String integerToRoman(int num)
  {
//Initialize the ans string
    String ans = "";
  //calculate the roman numbers
    while (num>0) {
        if (num >= 1000) {
            ans += "M";
            num -= 1000;
        }
      //check for all the corner cases like 900,400,90,40,9,4 etc.
        else if (num >= 900 && num < 1000) {
            ans += "CM";
            num -= 900;
        }
        else if (num >= 500 && num < 900) {
            ans += "D";
            num -= 500;
        }
        else if (num >= 400 && num < 500) {
            ans += "CD";
            num -= 400;
        }
        else if (num >= 100 && num < 400) {
            ans += "C";
            num -= 100;
        }
        else if (num >= 90 && num < 100) {
            ans += "XC";
            num -= 90;
        }
        else if (num >= 50 && num < 90) {
            ans += "L";
            num -= 50;
        }
        else if (num >= 40 && num < 50) {
            ans += "XL";
            num -= 40;
        }
        else if (num >= 10 && num < 40) {
            ans += "X";
            num -= 10;
        }
        else if (num == 9) {
            ans += "IX";
            num -= 9;
        }
        else if (num >= 5 && num < 9) {
            ans += "V";
            num -= 5;
        }
        else if (num == 4) {
            ans += "IV";
            num -= 4;
        }
        else if (num < 4) {
            ans += "I";
            num--;
        }
    }
  //return the result
    return ans;
}
  
// Driver program to test above function
  public static void main(String[] args)
  {
    System.out.println("Roman Numeral of Integer is:"
                       + integerToRoman(3549));
  }
}
//This code is contributed by Shivam Miglani


Python3




# Python Program for above approach
# Function to calculate roman equivalent
def intToRoman(num):
   
    # Initialize the ans string
    ans = ""
     
    # calculate the roman numbers
    while(num > 0):
        if(num >= 1000):
            ans += "M"
            num -= 1000
             
        # check for all the corner cases like 900,400,90,40,9,4 etc.
        elif(num >= 900 and num < 1000):
            ans += "CM"
            num -= 900
 
        elif(num >= 500 and num < 900):
            ans += "D"
            num -= 500
 
        elif(num >= 400 and num < 500):
            ans += "CD"
            num -= 400
 
        elif(num >= 100 and num < 400):
            ans += "C"
            num -= 100
 
        elif(num >= 90 and num < 100):
            ans += "XC"
            num -= 90
 
        elif(num >= 50 and num < 90):
            ans += "L"
            num -= 50
 
        elif(num >= 40 and num < 50):
            ans += "XL"
            num -= 40
 
        elif(num >= 10 and num < 40):
            ans += "X"
            num -= 10
 
        elif(num == 9):
            ans += "IX"
            num -= 9
 
        elif(num >= 5 and num < 9):
            ans += "V"
            num -= 5
 
        elif(num == 4):
            ans += "IV"
            num -= 4
 
        elif(num < 4):
            ans += "I"
            num = num - 1
 
    # return the result
    return ans
 
number = 3549
print(intToRoman(number))
 
# This code is contributed by Yash Agarwal(yashagarwal2852002)


C#




// C# program for above approach
using System;
using System.Collections.Generic;
 
public class GFG {
    static string intToRoman(int num)
    {
        // Initialize the ans string
        string ans = "";
        // calculate the roman numbers
        while (num > 0) {
            if (num >= 1000) {
                ans += "M";
                num -= 1000;
            }
            // check for all the corner cases like
            // 900,400,90,40,9,4 etc.
            else if (num >= 900 && num < 1000) {
                ans += "CM";
                num -= 900;
            }
            else if (num >= 500 && num < 900) {
                ans += "D";
                num -= 500;
            }
            else if (num >= 400 && num < 500) {
                ans += "CD";
                num -= 400;
            }
            else if (num >= 100 && num < 400) {
                ans += "C";
                num -= 100;
            }
            else if (num >= 90 && num < 100) {
                ans += "XC";
                num -= 90;
            }
            else if (num >= 50 && num < 90) {
                ans += "L";
                num -= 50;
            }
            else if (num >= 40 && num < 50) {
                ans += "XL";
                num -= 40;
            }
            else if (num >= 10 && num < 40) {
                ans += "X";
                num -= 10;
            }
            else if (num == 9) {
                ans += "IX";
                num -= 9;
            }
            else if (num >= 5 && num < 9) {
                ans += "V";
                num -= 5;
            }
            else if (num == 4) {
                ans += "IV";
                num -= 4;
            }
            else if (num < 4) {
                ans += "I";
                num--;
            }
        }
        // return the result
        return ans;
    }
 
    public static void Main(string[] args)
    {
        int number = 3549;
        Console.WriteLine(intToRoman(number));
    }
}
 
// This code is contributed by Kirti Agarwal


Javascript




// JavaScript Program for above approach
  
// Function to calculate roman equivalent
function intToRoman(num)
{
    // Initialize the ans string
    let ans = "";
    // calculate the roman numbers
    while(num != 0){
        if(num >= 1000){
            ans += "M";
            num -= 1000;
        }
        //check for all the corner cases like 900,400,90,40,9,4 etc.
        else if(num >= 900 && num < 1000){
            ans += "CM";
            num -= 900;
        }
        else if (num >= 500 && num < 900) {
            ans += "D";
            num -= 500;
        }
        else if (num >= 400 && num < 500) {
            ans += "CD";
            num -= 400;
        }
        else if (num >= 100 && num < 400) {
            ans += "C";
            num -= 100;
        }
        else if (num >= 90 && num < 100) {
            ans += "XC";
            num -= 90;
        }
        else if (num >= 50 && num < 90) {
            ans += "L";
            num -= 50;
        }
        else if (num >= 40 && num < 50) {
            ans += "XL";
            num -= 40;
        }
        else if (num >= 10 && num < 40) {
            ans += "X";
            num -= 10;
        }
        else if (num == 9) {
            ans += "IX";
            num -= 9;
        }
        else if (num >= 5 && num < 9) {
            ans += "V";
            num -= 5;
        }
        else if (num == 4) {
            ans += "IV";
            num -= 4;
        }
        else if (num < 4) {
            ans += "I";
            num--;
        }
    }
    // return the result
    return ans;
}
  
// Driver program to test above function
let number = 3549;
document.write(intToRoman(number));
 
// This code is contributed by Yash Agarwal(yashagarwal2852002)


Output

MMMDXLIX




Time Complexity: O(N), where N is the length of ans string that stores the conversion.
Auxiliary Space: O(N)

Approach 4: Using Recursion 

  1. First, we define a function called printRoman which takes an integer num as input.
  2. The function checks whether the input integer is greater than or equal to 1000. If it is, it prints the corresponding Roman numeral “M” and recursively calls the function with the updated input by subtracting 1000 from it.
  3. If the input integer is not greater than or equal to 1000, the function checks whether it is greater than or equal to 900. If it is, it prints the corresponding Roman numeral “CM” and recursively calls the function with the updated input by subtracting 900 from it.
  4. This process is repeated for each Roman numeral, with the function checking whether the input integer is greater than or equal to the corresponding value for each numeral. If it is, the function prints the corresponding numeral and recursively calls the function with the updated input by subtracting the corresponding value from it.
  5. Finally, if the input integer is less than 1, the function simply returns and the recursion ends.
  6. In the main function, we define an integer number and initialize it to 3549. We then call the printRoman function with this integer as input.
  7. The printRoman function prints the corresponding Roman numeral representation of the input integer (MMMDXLIX) to the console.

Below is the implementation of the above approach:

C++




#include <iostream>
using namespace std;
 
void printRoman(int num) {
    
    if(num >= 1000) {
        cout << "M";
        printRoman(num - 1000);
    }
    else if(num >= 900) {
        cout << "CM";
        printRoman(num - 900);
    }
    else if(num >= 500) {
        cout << "D";
        printRoman(num - 500);
    }
    else if(num >= 400) {
        cout << "CD";
        printRoman(num - 400);
    }
    else if(num >= 100) {
        cout << "C";
        printRoman(num - 100);
    }
    else if(num >= 90) {
        cout << "XC";
        printRoman(num - 90);
    }
    else if(num >= 50) {
        cout << "L";
        printRoman(num - 50);
    }
    else if(num >= 40) {
        cout << "XL";
        printRoman(num - 40);
    }
    else if(num >= 10) {
        cout << "X";
        printRoman(num - 10);
    }
    else if(num >= 9) {
        cout << "IX";
        printRoman(num - 9);
    }
    else if(num >= 5) {
        cout << "V";
        printRoman(num - 5);
    }
    else if(num >= 4) {
        cout << "IV";
        printRoman(num - 4);
    }
    else if(num >= 1) {
        cout << "I";
        printRoman(num - 1);
    }
}
 
int main() {
    int number = 3549;
    printRoman(number);
    return 0;
}


Java




import java.io.*;
// Nikunj Sonigara
public class GFG {
    public static void printRoman(int num) {
        if (num >= 1000) {
            System.out.print("M");
            printRoman(num - 1000);
        } else if (num >= 900) {
            System.out.print("CM");
            printRoman(num - 900);
        } else if (num >= 500) {
            System.out.print("D");
            printRoman(num - 500);
        } else if (num >= 400) {
            System.out.print("CD");
            printRoman(num - 400);
        } else if (num >= 100) {
            System.out.print("C");
            printRoman(num - 100);
        } else if (num >= 90) {
            System.out.print("XC");
            printRoman(num - 90);
        } else if (num >= 50) {
            System.out.print("L");
            printRoman(num - 50);
        } else if (num >= 40) {
            System.out.print("XL");
            printRoman(num - 40);
        } else if (num >= 10) {
            System.out.print("X");
            printRoman(num - 10);
        } else if (num >= 9) {
            System.out.print("IX");
            printRoman(num - 9);
        } else if (num >= 5) {
            System.out.print("V");
            printRoman(num - 5);
        } else if (num >= 4) {
            System.out.print("IV");
            printRoman(num - 4);
        } else if (num >= 1) {
            System.out.print("I");
            printRoman(num - 1);
        }
    }
 
    public static void main(String[] args) {
        int number = 3549;
        printRoman(number);
    }
}


Python3




def print_roman(num):
    if num >= 1000:
        print("M", end="")
        print_roman(num - 1000)
    elif num >= 900:
        print("CM", end="")
        print_roman(num - 900)
    elif num >= 500:
        print("D", end="")
        print_roman(num - 500)
    elif num >= 400:
        print("CD", end="")
        print_roman(num - 400)
    elif num >= 100:
        print("C", end="")
        print_roman(num - 100)
    elif num >= 90:
        print("XC", end="")
        print_roman(num - 90)
    elif num >= 50:
        print("L", end="")
        print_roman(num - 50)
    elif num >= 40:
        print("XL", end="")
        print_roman(num - 40)
    elif num >= 10:
        print("X", end="")
        print_roman(num - 10)
    elif num >= 9:
        print("IX", end="")
        print_roman(num - 9)
    elif num >= 5:
        print("V", end="")
        print_roman(num - 5)
    elif num >= 4:
        print("IV", end="")
        print_roman(num - 4)
    elif num >= 1:
        print("I", end="")
        print_roman(num - 1)
# Nikunj Sonigara
number = 3549
print_roman(number)


C#




using System;
 
class Program {
    // Function to print the Roman numeral representation of
    // a number
    static void PrintRoman(int num)
    {
        if (num >= 1000) {
            Console.Write("M");
            PrintRoman(num - 1000);
        }
        else if (num >= 900) {
            Console.Write("CM");
            PrintRoman(num - 900);
        }
        else if (num >= 500) {
            Console.Write("D");
            PrintRoman(num - 500);
        }
        else if (num >= 400) {
            Console.Write("CD");
            PrintRoman(num - 400);
        }
        else if (num >= 100) {
            Console.Write("C");
            PrintRoman(num - 100);
        }
        else if (num >= 90) {
            Console.Write("XC");
            PrintRoman(num - 90);
        }
        else if (num >= 50) {
            Console.Write("L");
            PrintRoman(num - 50);
        }
        else if (num >= 40) {
            Console.Write("XL");
            PrintRoman(num - 40);
        }
        else if (num >= 10) {
            Console.Write("X");
            PrintRoman(num - 10);
        }
        else if (num >= 9) {
            Console.Write("IX");
            PrintRoman(num - 9);
        }
        else if (num >= 5) {
            Console.Write("V");
            PrintRoman(num - 5);
        }
        else if (num >= 4) {
            Console.Write("IV");
            PrintRoman(num - 4);
        }
        else if (num >= 1) {
            Console.Write("I");
            PrintRoman(num - 1);
        }
    }
 
    static void Main(string[] args)
    {
        int number = 3549;
        PrintRoman(number);
    }
}


Javascript




function printRoman(num) {
    if (num >= 1000) {
        process.stdout.write("M");
        printRoman(num - 1000);
    } else if (num >= 900) {
        process.stdout.write("CM");
        printRoman(num - 900);
    } else if (num >= 500) {
        process.stdout.write("D");
        printRoman(num - 500);
    } else if (num >= 400) {
        process.stdout.write("CD");
        printRoman(num - 400);
    } else if (num >= 100) {
        process.stdout.write("C");
        printRoman(num - 100);
    } else if (num >= 90) {
        process.stdout.write("XC");
        printRoman(num - 90);
    } else if (num >= 50) {
        process.stdout.write("L");
        printRoman(num - 50);
    } else if (num >= 40) {
        process.stdout.write("XL");
        printRoman(num - 40);
    } else if (num >= 10) {
        process.stdout.write("X");
        printRoman(num - 10);
    } else if (num >= 9) {
        process.stdout.write("IX");
        printRoman(num - 9);
    } else if (num >= 5) {
        process.stdout.write("V");
        printRoman(num - 5);
    } else if (num >= 4) {
        process.stdout.write("IV");
        printRoman(num - 4);
    } else if (num >= 1) {
        process.stdout.write("I");
        printRoman(num - 1);
    }
}
 
const number = 3549;
printRoman(number);


Output

MMMDXLIX



Time complexity: O(n)
Auxiliary Space: O(n)

This article is contributed by Rahul Agrawal .If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments