Given an integer, convert it to a Roman numeral.
Input is guaranteed to being within the range from 1 to 3999.
Class Solution {public:string inttoroman (int num) {char symbol[] = {' I ', ' V ', ' X ', ' L ', ' C ', ' D ', ' M '}; int i = 6; int weight = 1000; string result; while (num) {const int digit = Num/weight; if (digit <= 3) {result.append (digit, symbol[i]); } else if (digit = = 4) {result.append (1, symbol[i]); Result.append (1, symbol[i+1]); } else if (digit = = 5) {result.append (1, symbol[i+1]); } else if (digit <= 8) {result.append (1, symbol[i+1]); Result.append (digit-5, symbol[i]); } else {result.append (1, symbol[i]); Result.append (1, symbol[i+2]); } num%= weight; Weight/= 10; I-= 2; } return result; }};
The key to this question is the understanding of Roman numeral rules.
Although the Roman numerals have seven basic characters, I think the understanding of the rules can begin with the I and v two characters.
I means that 1,v represents 5.
How to represent Arabic numerals 1-9?
You can use I to dine. such as I,ii, III
4, then 5-1, IV (the number on the left is smaller then minus).
5, that's V.
6~8, then with 5+, that is, first with a V, not enough with I to dine, such as VI, VII, VIII.
9, 10-1,10 will have to rely on the next set of Roman numerals to help.
The next group is 10, 50,
And then the next group is 100, 500,
But the group rules and I v are the same, but the symbols are not the same, the weights represent different.
IV in charge of single digit
XL in charge of 10 digits
The CD is in charge of the Hundred
MV in charge of thousands
XL is in charge of the million digit
CD in charge of 100,000 digits
...
This topic was tested to 3999, presumably because starting with 4000, you have to use the underlined characters.
Integer to Roman--Leetcode