NicolaBernini / CodingChallengesSolutions

CPP Code Snippets with comments
4 stars 4 forks source link

Coding Challenge - Integer to Roman and Roman to Integer #29

Open NicolaBernini opened 4 years ago

NicolaBernini commented 4 years ago

Overview

NicolaBernini commented 4 years ago

Solution

#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <unordered_map>
#include <assert.h>
using namespace std;

unordered_map<char, unsigned int> r2i_lut = { {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50} };

unsigned int r2i(const string& r)
{
    if(r.size()==0) return 0; 
    if(r.size()==1) return r2i_lut[r[0]]; 

    unsigned int res=0; 
    for(unsigned int i=0; i<r.size(); ++i)
    {
        if((i<r.size()-1) && (r2i_lut[r[i+1]] > r2i_lut[r[i]])) { res += (r2i_lut[r[i+1]] - r2i_lut[r[i]]); i++; }
        else { res += r2i_lut[r[i]]; } 
    }
    return res; 
}

// Function to convert decimal to Roman Numerals 
string i2r(unsigned int number) 
{ 
    string res; 
    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--) res+=sym[i]; 
      i--; 
    } 
    return res; 
} 

const vector<string> test_roman = 
    {
        "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", 
        "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", 
        "XXI", "XXII", "XXIII", "XXIV", "XXV", "XXVI", "XXVII", "XXVIII", "XXIX", "XXX", 
        "XXXI", "XXXII", "XXXIII", "XXXIV", "XXXV", "XXXVI", "XXXVII", "XXXVIII", "XXXIX", "XL", 
        "XLI", "XLII", "XLIII", "XLIV", "XLV", "XLVI", "XLVII", "XLVIII", "XLIX", "L"
    }; 

int main() {
    // your code goes here
    for(unsigned int i=0; i<test_roman.size();++i) {auto e = test_roman[i]; assert(r2i(e)==i+1); cout << r2i(e) << endl; }
    for(unsigned int i=0; i<50; ++i) { assert(test_roman[i].compare(i2r(i+1)) == 0 ); cout << i2r(i+1) << " Test " << test_roman[i] << endl;}
    return 0;
}

See it running on Ideone