Back to questions

Integer to Roman Palantir Python Interview Question

Integer to Roman

Palantir Python Interview Question

Before you solve this question, make sure to solve the easier warmup problem Roman to Integer, where you need to write a function that converts Roman numerals to integers.

In this problem, we're going the opposite direction – turning an integer into roman numerals. To refresh your memory, these seven different symbols represent Roman numerals with the following values:

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

Roman numerals are formed by converting decimal place values from highest to lowest. When converting an integer to a Roman numeral, follow these rules:

  1. For numbers that don’t start with 4 or 9: Pick the symbol with the largest value that can be subtracted from the number. Append that symbol to the result, subtract its value, and repeat the process with the remaining number.

  2. For numbers that start with 4 or 9: Use a subtractive form. This means you write one smaller symbol before a larger one. For example:

    • 4 is written as "IV" (1 less than 5),
    • 9 is written as "IX" (1 less than 10),
    • 40 is written as "XL" (10 less than 50),
    • 90 is written as "XC" (10 less than 100),
    • 400 is written as "CD" (100 less than 500),
    • 900 is written as "CM" (100 less than 1000).
  3. Symbols can be repeated up to three times for powers of 10: Only the symbols for 1 (I), 10 (X), 100 (C), and 1000 (M) can be repeated consecutively, up to three times, to represent multiples of those values. Symbols like 5 (V), 50 (L), and 500 (D) cannot be repeated. If you need to append a symbol four times, use the subtractive form instead (like "IV" for 4).

Given an integer less than 4000, return the Roman numeral representation of that number.

Examples:

Example 1:

Input: num=30num = 30

Output: "XXX"

Explanation:

  • 30 = XXX, where each X represents 10.
    Don’t worry, this is perfectly safe for work—just three Roman tens, nothing more!

Example 2:

Input: num=69num = 69

Output: "LXIX"

Explanation:

  • 69 is represented as LXIX: L = 50, X = 10, IX = 9.
  • Combining these gives us 50 + 10 + 9 = 69. Nice.

Input

(Python)

Output