223. Python Program to Convert a Number to Roman Numerals
HardPhase 3 · Challenge
This one takes a few steps. It uses two lists, a for loop and a while loop. You know all of them. Try a short example on paper first.
Overview
Roman numerals are the number system of ancient Rome. You still see them on clocks, in book chapters and in the years at the end of films. Turning numbers into them is a classic interview question.
Problem Statement
Sofia makes clock faces and book covers. Sofia needs numbers written in Roman numerals.
Roman numerals use letters for numbers:
| Letter | Value |
|---|---|
| I | 1 |
| V | 5 |
| X | 10 |
| L | 50 |
| C | 100 |
| D | 500 |
| M | 1000 |
The rules:
- Write the letters from the biggest value to the smallest, and add them up:
XVIis 10 + 5 + 1 = 16. - A letter can repeat up to 3 times in a row:
IIIis 3, andXXXis 30. - Six numbers put a smaller letter before a bigger one. This means "take the small one away":
IVis 4,IXis 9,XLis 40,XCis 90,CDis 400 andCMis 900. So 4 isIV, neverIIII.
Read a number. Print <number> in Roman numerals is <numeral>.
Examples
Example 1. Input 1994 gives:
1994 in Roman numerals is MCMXCIV
Why: 1994 is 1000 + 900 + 90 + 4. That is M, then CM, then XC, then IV.
Example 2. Input 58 gives:
58 in Roman numerals is LVIII
Why: 58 is 50 + 5 + 3. That is L, then V, then III.
Input
One whole number from 1 to 3999. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: the number, then in Roman numerals is, then the Roman numeral in capital letters, with one space between the parts. The tests try 10 different inputs, also 1, 4, 9 and 3999.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.