Integer to Roman
MediumString · Atlassian
Given an integer n, return its Roman numeral as an uppercase string.
Roman numerals use these symbols:
| Symbol | Value |
|---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
Build the numeral from the largest place value down (thousands, hundreds, tens, ones):
- Normally symbols are written largest to smallest and added up, e.g.
VIII= 8 andMDC= 1600. - A digit of 4 or 9 uses the subtractive form instead: a smaller symbol placed before a larger one. Only these six pairs are used:
IV(4),IX(9),XL(40),XC(90),CD(400),CM(900). I,X,C, andMmay repeat at most three times in a row;V,L, andDnever repeat.
Example 1
- Input:
- n = 2024
- Output:
- "MMXXIV"
- Explanation
- 2000 is
MM, the hundreds digit is 0 so nothing is written, 20 isXX, and 4 uses the subtractive formIV.
Example 2
- Input:
- n = 449
- Output:
- "CDXLIX"
- Explanation
- 400 is
CD, 40 isXL, and 9 isIX. Each 4 or 9 digit becomes one subtractive pair.
Example 3
- Input:
- n = 3888
- Output:
- "MMMDCCCLXXXVIII"
- Explanation
- No digit is 4 or 9, so every place is written additively:
MMM+DCCC+LXXX+VIII.
Constraints
- 1 ≤
n≤ 3999