Last active
May 8, 2024 18:58
-
-
Save b3x206/02ddc6e0d46bd53a39c60384254f2375 to your computer and use it in GitHub Desktop.
Converts a integer to a roman number.
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
#include <iostream> | |
#include <array> | |
#include <string> | |
#include <map> | |
// This is free and unencumbered software released into the public domain. | |
// Anyone is free to copy, modify, publish, use, compile, sell, or | |
// distribute this software, either in source code form or as a compiled | |
// binary, for any purpose, commercial or non-commercial, and by any | |
// means. | |
// (see https://unlicense.org) | |
// ---- | |
// @brief Converts a given integer to roman number | |
// (can be used with signed / unsigned integer) | |
// @param i [In] The number to convert. | |
// @returns std::string Resulting string. | |
template<typename TInt = int64_t> | |
std::string intToRomanNum(TInt i) | |
{ | |
static_assert(std::is_integral<TInt>::value, "[intToRomanNum] Type isn't an integer."); | |
std::string result; | |
// Check if number 0 (probably unneccesary to check if signed, just compare) | |
// (this can probably be 'if constexpr' in c++17) | |
if (std::is_signed<TInt>::value) | |
{ | |
if (i == 0) | |
{ | |
return std::string("0"); | |
} | |
if (i < 0) | |
{ | |
// append '-' to the target string and make given 'i' positive | |
// Probably not a valid rule but a fail-safe (because the while loop runs mindlessly) | |
result.append("-"); | |
i = -i; | |
} | |
} | |
else | |
{ | |
if (i == 0U) | |
{ | |
return std::string("0"); | |
} | |
} | |
// Define a persistent scoped map variable | |
static std::map<TInt, const char*> romNum; | |
if (romNum.empty()) | |
{ | |
romNum = | |
{ | |
{ 1, "I" }, | |
{ 4, "IV" }, | |
{ 5, "V" }, | |
{ 9, "IX" }, | |
{ 10, "X" }, | |
{ 40, "XL" }, | |
{ 90, "XC" }, | |
{ 100, "C" }, | |
{ 400, "CD" }, | |
{ 500, "D" }, | |
{ 900, "CM" }, | |
{ 1000, "M" } | |
}; | |
} | |
while (i > 0) | |
{ | |
for (auto pair = romNum.rbegin(); pair != romNum.rend(); pair++) | |
{ | |
while (i >= pair->first) | |
{ | |
i -= pair->first; | |
result.append(pair->second); | |
} | |
} | |
} | |
return result; | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
// Example program | |
std::cout << "-- Convert Num --" << std::endl; | |
int64_t a = 1; | |
while (a != 0) | |
{ | |
if (std::cin.bad()) | |
{ | |
std::cin.clear(); | |
} | |
std::cin >> a; | |
std::cout << "Number is : " << intToRomanNum(a) << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment