InterviewPrepKit

Home / Coding / Math & Geometry

Integer to Roman

medium Original β†—
Solving tips
  • Fold the six subtractive pairs (CM, CD, XC, XL, IX, IV) into the value table as first-class entries so the loop stays uniform.
  • Process the descending value/symbol table greedily: use divmod(num, value) to get both the repeat count and remainder in one step.
  • The table must be strictly descending by value for greedy to be correct; alternatively use per-digit lookup tables since num <= 3999.
  • Everything is bounded, so this is O(1) time and space.

Problem

Roman numerals use seven symbols: I=1, V=5, X=10, L=50, C=100, D=500, M=1000. Numbers are built by writing symbols from largest value to smallest and concatenating them, with six subtractive forms to avoid four-in-a-row: IV=4, IX=9, XL=40, XC=90, CD=400, CM=900. Given an integer num, convert it to its Roman numeral string.

Examples

  • num = 3 β†’ "III" β€” three ones.
  • num = 58 β†’ "LVIII" β€” 50 (L) + 5 (V) + 3 (III).
  • num = 1994 β†’ "MCMXCIV" β€” 1000 (M) + 900 (CM) + 90 (XC) + 4 (IV).

Constraints

  • 1 <= num <= 3999

Think about it first

Hint 1 Include the six subtractive pairs as if they were their own "symbols" with values 900, 400, 90, 40, 9, 4. Then every number is just a sum of values drawn from a fixed list.
Hint 2 Process the value/symbol pairs from largest to smallest. Greedily take as many copies of the current symbol as fit, subtract, and move on β€” this is optimal because Roman numerals are constructed exactly this way.
Hint 3 `divmod(num, value)` gives you both the repeat count and the remainder in one step. Alternatively, precompute per-digit tables (thousands, hundreds, tens, ones) and index into them.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.