Asked 4 months ago
0Comments
0 Views
Symbols and Values:
vector<string> symbols
: Contains the Roman numeral symbols in descending order of their values.vector<int> values
: Corresponding integer values for the Roman numeral symbols.Conversion Loop:
num
and add the corresponding symbol to the result string until num
is less than the current value.num = 3749
num = 3749
.1000
:
3749 >= 1000
: Subtract 1000
from 3749
, add M
to result.2749 >= 1000
: Subtract 1000
from 2749
, add M
to result.1749 >= 1000
: Subtract 1000
from 1749
, add M
to result.900
:
749 >= 900
: Skip.500
:
749 >= 500
: Subtract 500
from 749
, add D
to result.The final result is "MMMDCCXLIX"
, representing the integer 3749
.
#include <vector>
#include <string>
#include <iostream>
using namespace std;
string intToRoman(int num) {
// Define Roman symbols and their values
vector<string> symbols = {
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
};
vector<int> values = {
1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
};
string result = "";
for (int i = 0; i < values.size() && num > 0; ++i) {
while (num >= values[i]) {
num -= values[i]; // Subtract the current value from num
result += symbols[i]; // Append the corresponding symbol to result
}
}
return result;
}
int main() {
int num = 3749;
string result = intToRoman(num);
cout << result << " "; // Output: "MMMDCCXLIX"
return 0;
}
num -= values[i];
and result += symbols[i];
The two lines inside the loop are responsible for building the Roman numeral string by repeatedly subtracting the appropriate value from num
and adding the corresponding Roman numeral symbol to the result string.
while (num >= values[i]) {
num -= values[i];
result += symbols[i];
}
Condition: while (num >= values[i])
num
is greater than or equal to the current value.num
.Subtraction: num -= values[i];
num
.num
by the largest possible value that can still be subtracted without making num
negative.Appending Symbol: result += symbols[i];
result
string.Step-by-Step Execution
First Iteration (i = 0):
num = 3749
values[0] = 1000, symbols[0] = "M"
3749 >= 1000: True
Subtract 1000 from 3749 -> num = 2749
Append "M" to result -> result = "M"
2749 >= 1000: True
Subtract 1000 from 2749 -> num = 1749
Append "M" to result -> result = "MM"
1749 >= 1000: True
Subtract 1000 from 1749 -> num = 749
Append "M" to result -> result = "MMM"
749 >= 1000: False (move to next value)
Second Iteration (i = 1):
num = 749
values[1] = 900, symbols[1] = "CM"
749 >= 900: False (move to next value)
Third Iteration (i = 2):
num = 749
values[2] = 500, symbols[2] = "D"
749 >= 500: True
Subtract 500 from 749 -> num = 249
Append "D" to result -> result = "MMMD"
249 >= 500: False (move to next value)
Continue this process for the remaining values until num becomes 0.
Share