57. Number to Old Numerals

An archive prints page numbers in an old numeral system with the symbols I = 1, V = 5, X = 10, L = 50, C = 100, D = 500 and M = 1000. The usual rules apply: symbols are written from largest to smallest and added, except that these six subtractive forms are used instead of repeating a symbol four times: IV = 4, IX = 9, XL = 40, XC = 90, CD = 400 and CM = 900.

Given a whole number num, return its numeral as a string, always using the shortest valid form.

Example 1

Input:
num = 29
Output:
"XXIX"
Explanation:

29 is 20 + 9, written XX followed by IX.

Example 2

Input:
num = 2044
Output:
"MMXLIV"
Explanation:

2044 is 2000 + 40 + 4, written MM, XL and IV.

Constraints

1 ≤ num ≤ 3999

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(1)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…