- The Modern C++ Challenge
- Marius Bancila
- 384字
- 2021-06-25 22:01:24
11. Converting numerical values to Roman
Roman numerals, as they are known today, use seven symbols: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, and M = 1000. The system uses additions and subtractions in composing the numerical symbols. The symbols from 1 to 10 are I, II, III, IV, V, VI, VII, VIII, IX, and X. Romans did not have a symbol for zero and used to write nulla to represent it. In this system, the largest symbols are on the left, and the least significant are on the right. As an example, the Roman numeral for 1994 is MCMXCIV. If you are not familiar with the rules for Roman numerals, you should read more on the web.
To determine the Roman numeral of a number, use the following algorithm:
- Check every Roman base symbol from the highest (M) to the lowest (I)
- If the current value is greater than the value of the symbol, then concatenate the symbol to the Roman numeral and subtract its value from the current one
- Repeat until the current value reaches zero
For example, consider 42: the first Roman base symbol smaller than 42 is XL, which is 40. We concatenate it to the numeral, resulting in XL, and subtract from the current number, resulting in 2. The first Roman base symbol smaller than 2 is I, which is 1. We add that to the numeral, resulting in XLI, and subtract 1 from the number, resulting in 1. We add one more I to the numeral, which becomes XLII, and subtract again 1 from the number, reaching 0 and therefore stopping:
std::string to_roman(unsigned int value)
{
std::vector<std::pair<unsigned int, char const*>> roman {
{ 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" }};
std::string result;
for (auto const & kvp : roman) {
while (value >= kvp.first) {
result += kvp.second;
value -= kvp.first;
}
}
return result;
}
This function can be used as follows:
int main()
{
for(int i = 1; i <= 100; ++i)
{
std::cout << i << "\t" << to_roman(i) << std::endl;
}
int number = 0;
std::cout << "number:";
std::cin >> number;
std::cout << to_roman(number) << std::endl;
}
- 深入淺出Java虛擬機:JVM原理與實戰
- 構建移動網站與APP:HTML 5移動開發入門與實戰(跨平臺移動開發叢書)
- INSTANT MinGW Starter
- Learning Informatica PowerCenter 10.x(Second Edition)
- 精通API架構:設計、運維與演進
- Java設計模式及實踐
- Hands-On Microservices with Kotlin
- Big Data Analytics
- Hands-On Full Stack Development with Go
- Mastering C++ Multithreading
- PHP 7從零基礎到項目實戰
- Android智能手機APP界面設計實戰教程
- C# 7.0本質論
- 網絡綜合布線與組網實戰指南
- Mastering Magento Theme Design