Skip to content

Instantly share code, notes, and snippets.

@timothyqiu
Created March 12, 2015 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timothyqiu/2f66f5362da8d18e3fb3 to your computer and use it in GitHub Desktop.
Save timothyqiu/2f66f5362da8d18e3fb3 to your computer and use it in GitHub Desktop.
将 1~3999 内的整数正确转换至罗马数字
#include <algorithm>
#include <cassert>
#include <string>
std::string toRoman(int number)
{
static struct {
int value;
char const *symbols;
} const mapping[] = {
{ 1000, "M" },
{ 900, "CM" },
{ 500, "D" },
{ 400, "CD" },
{ 100, "C" },
{ 90, "XC" },
{ 50, "L" },
{ 40, "XL" },
{ 10, "X" },
{ 9, "IX" },
{ 5, "V" },
{ 4, "IV" },
{ 1, "I" },
};
assert(number > 0);
std::string roman;
for (auto iter = std::begin(mapping);
iter != std::end(mapping) && number > 0;
++iter)
{
int count = number / iter->value;
number = number % iter->value;
for (int i = 0; i< count; i++) {
roman.append(iter->symbols);
}
}
return roman;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment