Problem 12

Abstract / Summary

Convert a number from 1 to 3999 into its roman numeral representation following standard roman numeral rules.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0012.cpp

class Solution {
public:
    string intToRoman(int num) {
        string result;

        while (num >= 1000) { result += "M";  num -= 1000; }
        while (num >=  900) { result += "CM"; num -=  900; }
        while (num >=  500) { result += "D";  num -=  500; }
        while (num >=  400) { result += "CD"; num -=  400; }
        while (num >=  100) { result += "C";  num -=  100; }
        while (num >=   90) { result += "XC"; num -=   90; }
        while (num >=   50) { result += "L";  num -=   50; }
        while (num >=   40) { result += "XL"; num -=   40; }
        while (num >=   10) { result += "X";  num -=   10; }
        while (num >=    9) { result += "IX"; num -=    9; }
        while (num >=    5) { result += "V";  num -=    5; }
        while (num >=    4) { result += "IV"; num -=    4; }
        while (num >=    1) { result += "I";  num -=    1; }

        return result;
    }
};
22 lines | 930 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 71% (3+ million submissions).

Typical patterns to solve this problem:
  • Hash Table
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation converts an integer in the range typically required for Roman numeral representation (1 - 3999) into its canonical Roman string. The algorithm proceeds by repeatedly subtracting the largest possible Roman value from the input while appending the corresponding symbol to an output string. The control flow is expressed as a series of while loops, each dedicated to a specific numeral or subtractive pair.

Key Steps

Initialization

The method begins by declaring an empty string named result. This variable accumulates the Roman symbols as the algorithm progresses.

string result;

Processing Thousands

The first loop handles the symbol for one thousand (M). As long as the remaining number is at least 1000, the loop appends an M and reduces the number by 1000. This directly maps the highest place value without any special cases.

while (num >= 1000) { result += "M";  num -= 1000; }

Handling Subtractive Notation for Nine Hundred

Roman numerals use a subtractive form for 900 (CM). The second loop checks for this exact value, appends CM, and subtracts 900. This ensures that numbers like 1900 are rendered as MCM rather than DCCCC.

while (num >=  900) { result += "CM"; num -=  900; }

Processing Five Hundred

The third loop deals with the standard symbol for five hundred (D). It continues to append D while the remaining number is at least 500.

while (num >=  500) { result += "D";  num -=  500; }

Subtractive Notation for Four Hundred

The fourth loop captures the subtractive pair for 400 (CD). By checking this condition before the generic hundred loop, the algorithm respects the canonical form.

while (num >=  400) { result += "CD"; num -=  400; }

Processing Hundreds

The next loop appends C for each remaining hundred. This loop runs after the special cases for 900 and 400, guaranteeing correct ordering.

while (num >=  100) { result += "C";  num -=  100; }

Subtractive Notation for Ninety

The algorithm then checks for 90 (XC) and handles it similarly to other subtractive pairs.

while (num >=   90) { result += "XC"; num -=   90; }

Processing Fifty

The loop for fifty (L) follows, appending L while the remainder is at least 50.

while (num >=   50) { result += "L";  num -=   50; }

Subtractive Notation for Forty

The forty case (XL) is captured next, ensuring that numbers like 40 are rendered as XL.

while (num >=   40) { result += "XL"; num -=   40; }

Processing Tens

The ten loop adds X for each remaining ten.

while (num >=   10) { result += "X";  num -=   10; }

Subtractive Notation for Nine

The nine case (IX) is handled before the five and four loops, preserving the subtractive pattern.

while (num >=    9) { result += "IX"; num -=    9; }

Processing Five

The five loop appends V when the remainder reaches at least five.

while (num >=    5) { result += "V";  num -=    5; }

Subtractive Notation for Four

The four case (IV) is processed next, guaranteeing that 4 becomes IV rather than IIII.

while (num >=    4) { result += "IV"; num -=    4; }

Processing Units

Finally, the unit loop adds I for each remaining one, completing the conversion.

while (num >=    1) { result += "I";  num -=    1; }

Return Value

After all loops have exhausted the input number, the accumulated result string is returned as the Roman numeral representation.

return result;

Edge Cases Handled

The algorithm explicitly includes the six subtractive forms (CM, CD, XC, XL, IX, IV). By placing these checks before the corresponding additive loops, it correctly renders numbers that would otherwise be expressed with repeated symbols. For example, the value 944 is processed as CM (900) followed by XL (40) and IV (4), yielding CMXLIV.

Because each loop reduces the number by the exact value it represents, the method naturally terminates when the input reaches zero, covering the lower bound of the valid range. The sequence of checks also guarantees that no illegal combinations (such as IL for 49) can be produced.

Performance Optimizations

The design relies on a fixed sequence of while loops, each performing a simple comparison, a string concatenation, and a subtraction. The number of iterations is bounded by the maximum count of any Roman symbol in a valid numeral (for instance, at most three consecutive Ms for 3000). Consequently, the total number of loop executions is limited and independent of the magnitude of the input beyond the defined range.

String concatenation is performed using the += operator on a std::string. Since the total length of the resulting Roman numeral is small (no more than 15 characters for the highest allowed value), the overhead of repeated concatenations is negligible. The algorithm avoids more expensive operations such as division or modulus, relying solely on subtraction, which is a low-cost integer operation.

The sequential ordering of the loops ensures that the largest possible symbol is always chosen first, minimizing the number of iterations required to reduce the input to zero. This greedy approach eliminates the need for additional data structures or look-up tables, keeping the runtime footprint minimal.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of special blocks that represent numbers. Some blocks are worth a lot, like M which is worth one thousand, and some are tiny, like I which is worth just one.

The code looks at the big number you gave it and tries to break it down into these smaller blocks starting with the biggest ones first. It checks if the number is large enough to fit a big block. If it fits, it grabs that block, puts it in a row to save for later, and then takes that amount away from your pile. It keeps doing this over and over again, checking for giant blocks and then smaller and smaller ones, until there is nothing left in the pile. By the time it finishes, all those blocks are lined up in a neat row to show the number in a different way.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 29 | median = 8 | μ = 7.62 | σ = 0.76

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# C Rust Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JS
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Java
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Java
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
56 links | 38 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Integer to Roman - Leetcode 12 - Python'
NeetCode 10 mins
Integer to Roman - Leetcode 12 - Python
YouTube video 'DSA Phir se with Sumeet | Leetcode 12 | Integer to Roman'
Pepcoding 12 mins
DSA Phir se with Sumeet | Leetcode 12 | Integer to Roman
YouTube video 'Integer to Roman - LeetCode 12 - Coding Interview Questions'
One Code Man 4 mins
Integer to Roman - LeetCode 12 - Coding Interview Questions
YouTube video 'Integer to Roman  || String 3|| Placement Preparation Series || Optimized || C++ || Leetcode 12 ||'
Bro Coders 12 mins
Integer to Roman || String 3|| Placement Preparation Series || Optimized || C++ || Leetcode 12 ||
YouTube video 'Integer to Roman - LeetCode 12 - Python #leetcode #leetcode150 #topinterview150'
Deepti Talesra 11 mins
Integer to Roman - LeetCode 12 - Python #leetcode #leetcode150 #topinterview150
YouTube video 'Integer to Roman Python Solution - LeetCode #12'
Professor Oakes 6 mins
Integer to Roman Python Solution - LeetCode #12
YouTube video 'Leetcode Question 12 "Integer to Roman" in Javascript'
Ghumman Tech 5 mins
Leetcode Question 12 "Integer to Roman" in Javascript
YouTube video 'LeetCode in C# | 12. Integer to Roman'
Josh Ackland 8 mins
LeetCode in C# | 12. Integer to Roman
YouTube video 'Integer to Roman | Leetcode 12'
Coding Decoded 7 mins
Integer to Roman | Leetcode 12
YouTube video 'Integer to Roman - Leetcode 12 - JavaScript Solution'
Web Coder Abhishek 6 mins
Integer to Roman - Leetcode 12 - JavaScript Solution
YouTube video 'Daily Leetcode #933: Oct 20, 2022 - 12. Integer to Roman'
Programming Live with Larry 14 mins
Daily Leetcode #933: Oct 20, 2022 - 12. Integer to Roman
YouTube video 'ASMR Leetcode #12 : Integer to Roman Python solution'
ExtremeProgrammer 3 mins
ASMR Leetcode #12 : Integer to Roman Python solution
YouTube video 'Daily Leetcode #344: Mar 10, 2021 - 12. Integer to Roman'
Programming Live with Larry 19 mins
Daily Leetcode #344: Mar 10, 2021 - 12. Integer to Roman
YouTube video '12. Integer to Roman ||Leetcode Daily Medium || String || CPP'
Komal Pal 21 mins
12. Integer to Roman ||Leetcode Daily Medium || String || CPP
YouTube video 'Leetcode | Top Interview 150 | Medium | 12. Integer to Roman | Time: O(N) | Javascript'
Software Interviews Prep 11 mins
Leetcode | Top Interview 150 | Medium | 12. Integer to Roman | Time: O(N) | Javascript
YouTube video 'Integer to Roman | LeetCode 12 | Java | 2 Approach w/ Code | @LearnOverflow'
Learn Overflow 12 mins
Integer to Roman | LeetCode 12 | Java | 2 Approach w/ Code | @LearnOverflow
YouTube video 'LeetCode: 12. Integer to Roman (Visualized)'
Code With Zi 16 mins
LeetCode: 12. Integer to Roman (Visualized)
YouTube video 'LeetCode 12 | Integer to Roman | Array | Recursion | Java'
Sleepy Cracker 7 mins
LeetCode 12 | Integer to Roman | Array | Recursion | Java
YouTube video 'Leetcode 12: Integer to Roman'
Algorithms Casts 13 mins
Leetcode 12: Integer to Roman
YouTube video 'Integer to Roman | LeetCode 12 | Coders Camp'
Coders Camp 6 mins
Integer to Roman | LeetCode 12 | Coders Camp
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality