Created
October 3, 2016 22:16
-
-
Save jniemann66/cd8b5a45cf45b2eaded69abae72a4e11 to your computer and use it in GitHub Desktop.
decimal to roman numerals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DecimalToRoman.cpp : convert decimal number to Roman Numeral | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
struct symbol { | |
std::string name; | |
int value; | |
}; | |
std::vector<symbol> symbols= { | |
{"M",1000}, | |
{"CM",900}, | |
{"D",500}, | |
{"CD",400}, | |
{"C",100}, | |
{"XC",90}, | |
{"L",50}, | |
{"XL",40}, | |
{"X",10}, | |
{"IX",9}, | |
{"V",5}, | |
{"IV",4}, | |
{"I",1} | |
}; | |
std::string dec2Roman(int n, std::vector<symbol>::iterator i = symbols.begin()); | |
int main(int argc, char** argv) | |
{ | |
if (argc == 2) { | |
std::cout << dec2Roman(atoi(argv[1])) << std::endl; | |
return EXIT_SUCCESS; | |
} | |
else { | |
std::cout << "Usage: " << argv[0] << " <decimal number>" << std::endl; | |
return EXIT_FAILURE; | |
} | |
} | |
std::string dec2Roman(int n, std::vector<symbol>::iterator i) { | |
std::string output(""); | |
if (i != symbols.end()) { | |
while (n >= i->value) { | |
n -= i->value; | |
output.append(i->name); | |
} | |
if (n > 0) | |
output.append(dec2Roman(n, ++i)); | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment