Little Puzzlers–Positive Integer to Roman Numerals

I like to keep my brain sharp by working on programming puzzlers. On off weeks I'm going to start posting programming puzzlers I've collected over the years. Hopefully you'll find them as entertaining as I do.

There’s really no “ah-hah!” moment with this problem, but it is still – I find – a good programming problem for seeing how well a candidate’s mind works in structuring logic and finding patterns.

The Problem

Given a positive integer (i.e. > 0), please return a string representation of that integer using Roman Numerals.  You may assume IV for four, though you can optionally use IIII if you prefer the standard clock representation of 4.

Interesting side note: some say that the reason IIII is used instead of IV on clocks is because IV represented the Roman god Jove, and thus was omitted from the clock face to avoid “blasphemy”.

If you’re not familiar with Roman Numerals, you can find a good primer nearly anywhere on the internet (such as here on Wikipedia), though the basics are:

  • I = 1
  • V = 5
  • X = 10
  • L = 50
  • C = 100
  • D = 500
  • M = 1000

Roman numerals are generally written from highest denominate to lowest denomination, except where the previous “unit” letter is used to create 1 of the previous “unit” less than the next. 

  • I can be placed before V and X to make 4 (IV) and 9 (IX) respectively
  • X can be placed before L and C to make 40 (XL) and 90 (XC) respectively
  • C can be placed before D and M to make 400 (CD) and 900 (CM) respectively.

Note that V, L, and D are not used to prefix the next number since this would obviously be redundant (i.e. VX is the same as V, LC is the same as L). 

Spoiler Alert!

Fair Warning: there may be discussion of the problem and potential solutions posted in the comments below. Read at your own risk.

This article is part of the GWB Archives. Original Author: James Michael Hare

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.