The Roman numerals contain the following seven characters:,,,, I
V
X
L
C
, D
and M
.
Character value I 1V 5X 10L 50C 100D 500M 1000
For example, the Roman numeral 2 is written II
, that is, two parallel 1. 12 Write XII
, that is X
+ II
. 27 Write XXVII
, that is XX
+ V
+ II
.
Usually, the number of Roman numerals is small and the numbers are on the right side of the large numbers. But there are exceptions, such as 4 not IIII
to write, but IV
. The number 1 is on the left side of the number 5, the number represented is equal to the large number 5 decreases the number 1 gets the value 4. Similarly, the number 9 is represented as IX
. This special rule applies only to the following six cases:
I
Can be placed on V
X
the left side of (5) and (10) to represent 4 and 9.
X
Can be placed on L
C
the left side of (50) and (100) to represent 40 and 90.
C
Can be placed on D
M
the left side of (500) and (1000) to represent 400 and 900.
Given an integer, convert it to Roman numerals. The input is guaranteed to be within the range of 1 to 3999.
Example 1:
Input: 3 output: "III"
Example 2:
Input: 4 output: "IV"
Example 3:
Input: 9 output: "IX"
Example 4:
Input: 58 Output: "LVIII" Explanation: C = +, L = +, XXX = +, III = 3.
Example 5:
Input: 1994 Output: "MCMXCIV" Explanation: M = +, CM =-, XC = +, IV = 4.
classSolution { PublicString Inttoroman (intnum) { int[] numarray=New int[]{1000,900,500,400,100,90,50,40,10,9,5,4,1}; String[] Romaarray=Newstring[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; StringBuffer SB=NewStringBuffer (); if(num<0| | num>3999) return NULL; for(inti=0;i<numarray.length;i++) { inttemp=num/Numarray[i]; while(temp>0) {sb.append (romaarray[i]); Temp--; } num=num%Numarray[i]; } returnsb.tostring (); }}
Submit Results
Leetcode integer to Roman numeral Java