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;
}
};
Difficulty
and has an acceptance rate of about 71% (3+ million submissions).
Typical patterns to solve this problem:
- Hash Table
- Math
- String
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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 |
Videos
Similar Problems
- problem 13: Roman to Integer
- problem 273: Integer to English Words
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- 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