Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
NicolaBernini opened this issue Feb 22, 2020 · 1 comment
Open

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

NicolaBernini opened this issue Feb 22, 2020 · 1 comment
Assignees

Comments

@NicolaBernini
Copy link
Owner

NicolaBernini commented Feb 22, 2020

Overview

  • Develop a function able to convert integers from 1 to 50 into Roman
  • Develop a function able to convert Roman from 1 to 50 into integers
@NicolaBernini
Copy link
Owner Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant