Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Popularize the Rome notation
The Base
I-1
V-5
X-10
L-50
C-100
D-500
M-1000
If a lower value symbol is before a higher value one, it is subtracted. Otherwise it is added.
So 'iv 'is '4' and 'vi' is '6 '.
For the numbers above X, only the symbol right before it may be subtracted: So 99 is:Xcix(And notIC).
Note that 4 = IV, 9 = IX, 40 = XL, 90 = XC, 400 = Cd, 900 = cm
The method is very simple. Set up the base number and the character representation corresponding to each base number, and then perform the integer and remainder operations in sequence. The algorithm is relatively simple and you can directly view the Code:
1 class solution {2 public: 3 string inttoroman (INT num) {4 int base [] = {1, 4, 5, 9, 10, 40, 50, 90,100,400,500,900,100 0 }; // The base numbers correspond to the characters in romanchar to 5 char * romanchar [] = {"I", "IV", "V", "IX", "X ", "XL", "L", "XC", "C", "cd", "D", "cm", "M"}; 6 string ans; 7 For (INT I = 12; I> = 0; -- I) {// start from the last base 8 int CNT = num/base [I]; // a bit similar to the simulated 10-digit system. the number on the I-bit is 9 num % = base [I]; // 0 ~ The I-1 bit is the remaining number 10 while (CNT --) ans. append (romanchar [I]); // converts to romanchar11} 12 Return ans; 13} 14 };
Roman to integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Integer to Roman