Integer to Roman using c++

 Integer to Roman using C++

We have to convert the given integer into Roman numerals.
Here is the value and its corresponding roman numeral:

   Integer    Roman

        1               I
        5              V
        10            X
        50            L
        100          C
        500          D
        1000        M

From this table, we convert any integer into its Roman numeral like:
    3 can be written using a roman numeral of 1 thrice i.e III
    8 can be written as 5+3 so for 5, V and for 3, III so 8 will be VIII

but there are some exceptions like for 4 we can't write IIII, it's wrong.
so here we will use roman of 1 before roman of 5, i.e for 4 roman will be IV.

similarly for other exceptions use:
  • I will be placed before X to make it 9 
  • X before L to make it 40
  • X before C to make it 90
  • C before D to make 400
  • C before M to make 900

Algorithm

Here we will be using hashmap where we will store the roman numeral of 1,4,9,10,40,50,90,100,400,500,900,1000 in descending order.
Now we will divide the number with the key and add the value of remainder in my answer string for quotient number of time and also update the number with the value of remainder we got. we will run this loop till our number becomes 0.
return the answer string.

C++ Code

string intToRoman(int num) {
        string ans;
        int div;
        map<int,string,greater<int>> mpp;
        mpp[1]="I";
        mpp[5]="V";
        mpp[10]="X";
        mpp[50]="L";
        mpp[100]="C";
        mpp[500]="D";
        mpp[1000]="M";
        mpp[4]="IV";mpp[9]="IX";mpp[40]="XL";mpp[90]="XC";mpp[400]="CD";mpp[900]="CM";
        for(auto pr: mpp){
            if(num<0){
                return ans;
            }
            div=num/pr.first;
            num%=pr.first;
            while(div){
                ans+=pr.second;
                div--;
            }
        }
        return ans;
    }

Comments

Popular posts from this blog

NITs Gate Vlsi cutoff

Swap Nodes in Pairs using recursion in cpp