Created
March 12, 2015 05:10
-
-
Save timothyqiu/2f66f5362da8d18e3fb3 to your computer and use it in GitHub Desktop.
将 1~3999 内的整数正确转换至罗马数字
This file contains hidden or 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 <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