TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
decimal_to_roman_numeral.cpp
Go to the documentation of this file.
1
7#include <cmath>
8#include <cstdio>
9#include <cstring>
10#include <iostream>
11
15std::string fill(char c, int n) {
16 std::string s = "";
17 while (n--) s += c;
18 return s;
19}
20
24std::string tolowerRoman(int n) {
25 if (n < 4)
26 return fill('i', n);
27 if (n < 6)
28 return fill('i', 5 - n) + "v";
29 if (n < 9)
30 return std::string("v") + fill('i', n - 5);
31 if (n < 11)
32 return fill('i', 10 - n) + "x";
33 if (n < 40)
34 return fill('x', n / 10) + tolowerRoman(n % 10);
35 if (n < 60)
36 return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10);
37 if (n < 90)
38 return std::string("l") + fill('x', n / 10 - 5) + tolowerRoman(n % 10);
39 if (n < 110)
40 return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10);
41 if (n < 400)
42 return fill('c', n / 100) + tolowerRoman(n % 100);
43 if (n < 600)
44 return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100);
45 if (n < 900)
46 return std::string("d") + fill('c', n / 100 - 5) +
47 tolowerRoman(n % 100);
48 if (n < 1100)
49 return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100);
50 if (n < 4000)
51 return fill('m', n / 1000) + tolowerRoman(n % 1000);
52 return "?";
53}
54
58std::string toupperRoman(int n) {
59 if (n < 4)
60 return fill('I', n);
61 if (n < 6)
62 return fill('I', 5 - n) + "V";
63 if (n < 9)
64 return std::string("V") + fill('I', n - 5);
65 if (n < 11)
66 return fill('I', 10 - n) + "X";
67 if (n < 40)
68 return fill('X', n / 10) + toupperRoman(n % 10);
69 if (n < 60)
70 return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10);
71 if (n < 90)
72 return std::string("L") + fill('X', n / 10 - 5) + toupperRoman(n % 10);
73 if (n < 110)
74 return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10);
75 if (n < 400)
76 return fill('C', n / 100) + toupperRoman(n % 100);
77 if (n < 600)
78 return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100);
79 if (n < 900)
80 return std::string("D") + fill('C', n / 100 - 5) +
81 toupperRoman(n % 100);
82 if (n < 1100)
83 return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100);
84 if (n < 4000)
85 return fill('M', n / 1000) + toupperRoman(n % 1000);
86 return "?";
87}
88
90int main() {
91 int n;
92 std::cout << "\t\tRoman numbers converter\n\n";
93 std::cout << "Type in decimal number between 0 up to 4000 (exclusive): ";
94 std::cin >> n;
95 std::cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n";
96 std::cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n";
97 return 0;
98}
std::string tolowerRoman(int n)
std::string toupperRoman(int n)
std::string fill(char c, int n)