Example:
Input : 515 Output : DXV
In Roman Numeric System, below symbols are used to represent any number.
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1,000
I placed before V or X indicates one less, so four is IV (one less than five) and nine is IX (one less than ten)
X placed before L or C indicates ten less, so forty is XL (ten less than fifty) and ninety is XC (ten less than a hundred)
C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand)[5]
1. Initialize a String
variable to store the final output.
2. For every 1000 present in the input, append "M" to the output.
3. If the input is greater than/equal to 900
, append "CM"
to the output and subtract 900
from the input.
4. If the input is greater than/equal to 500
, append "D"
to the output and subtract 500
from the input.
5. If the input is greater than/equal to 400
, append "CD"
to the output and subtract 400
from the input.
6. If the input is greater than/equal to 100
, append "C"
to the output and subtract 100
from the input.
7. If the input is greater than/equal to 90
, append "XC"
to the output and substract 90
from the input.
8. If the input is greater than/equal to 50
, append "L"
to the output and substract 50
from the input.
9. If the input is greater than/equal to 40
, append "XL"
to the output and substract 40
from the input.
10. If the input is greater than/equal to 10
, append "X"
to the output for every 10
present in the input.
11. If the input is greater than/equal to 9
, append "IX"
to the ouput and substract 9
from the input.
12. If the input is greater than/equal to 5
, append "V"
to the output and substract 5
from the input.
13. If the input is greater than/equal to 4
, append "IV"
to the output and substract 4
out of it.
14. For every 1 present in the input, append "I"
to the output, till the input becomes 0.
15. Return the output.
public static String intToRoman(int input) { }
C
Java
Python