- 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;
}
- Learn ECMAScript(Second Edition)
- 深入核心的敏捷開發:ThoughtWorks五大關鍵實踐
- Advanced Machine Learning with Python
- 前端跨界開發指南:JavaScript工具庫原理解析與實戰
- Python for Secret Agents:Volume II
- 認識編程:以Python語言講透編程的本質
- 名師講壇:Spring實戰開發(Redis+SpringDataJPA+SpringMVC+SpringSecurity)
- Apache Mahout Clustering Designs
- Learning Concurrent Programming in Scala
- Express Web Application Development
- Maker基地嘉年華:玩轉樂動魔盒學Scratch
- OpenMP核心技術指南
- Deep Learning with R Cookbook
- Application Development with Parse using iOS SDK
- Python 3快速入門與實戰