Question:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Question Analysis:
After reading the questions for a long time, I couldn't understand what Roman numeral was. So I checked it online and found out what it was, indicating that it was speechless.
Simulation questions:
Basic Characters |
I |
V |
X |
L |
C |
D |
M |
Meanings of corresponding Arabic numerals |
1 |
5 |
10 |
50 |
100 |
500 |
1000 |
1. For the same number, the number is equal to the sum of the numbers, for example, III = 3;
2. If a small number is on the left of a large number, the number is equal to the number reduced by a large number, for example, IV = 4; ix = 9;
3. If a small number is on the right of a large number, the number is equal to the value of a large number plus a small number. For example, Vi = 6; xi = 11;
Code:
class Solution{public: void setDigit(string &res,int n,char a,char b,char c){ if(n<4){ for(int i=0;i<n;i++){ res.push_back(a); } } else if(n==4){ res.push_back(a); res.push_back(b); } else if(n==5){ res.push_back(b); } else if(n>5 && n<9){ res.push_back(b); for(int i=5;i<n;i++){ res.push_back(a); } } else if(n==9){ res.push_back(a); res.push_back(c); } } string intToRoman(int num){ int a1=(num/1000)%10,a2=(num/100)%10,a3=(num/10)%10,a4=num%10; setDigit(res,a1,‘M‘,‘?‘,‘?‘); setDigit(res,a2,‘C‘,‘D‘,‘M‘); setDigit(res,a3,‘X‘,‘L‘,‘C‘); setDigit(res,a4,‘I‘,‘V‘,‘X‘); return res; }};
Refer to what someone else wrote...
Leetcode-integer to Roman