C++ 0013.cpp
class Solution {
public:
int romanToInt(string s) {
char prev = 0;
int result = 0;
for (auto c : s)
{
switch (c)
{
case 'I': result++; break;
case 'V': if (prev == 'I') result += 5-2*1; else result += 5; break;
case 'X': if (prev == 'I') result += 10-2*1; else result += 10; break;
case 'L': if (prev == 'X') result += 50-2*10; else result += 50; break;
case 'C': if (prev == 'X') result += 100-2*10; else result += 100; break;
case 'D': if (prev == 'C') result += 500-2*100; else result += 500; break;
case 'M': if (prev == 'C') result += 1000-2*100; else result += 1000; break;
}
prev = c;
}
return result;
}
};
Difficulty
and has an acceptance rate of about 67% (9+ 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 presented implementation converts a Roman-numeral string into its integer value. It processes the input sequentially, maintaining a running total and a reference to the previously examined character. By inspecting the current character together with the previous one, the algorithm correctly accounts for the subtractive forms defined by Roman-numeral conventions.
Core Logic
The conversion is performed inside a single for-range loop that iterates over each character of the input string. Two local variables are declared before the loop: prev, initialized to zero, stores the character processed in the prior iteration, and result, initialized to zero, accumulates the numeric value.
char prev = 0;
int result = 0;
for (auto c : s)
{
// switch handling omitted here
prev = c;
}
return result;
Within the loop a switch statement selects the action based on the current character c. For each Roman symbol the code either adds its base value directly or, when a subtractive pattern is detected, adjusts the addition to reflect the subtraction.
Handling Subtractive Notation
Roman numerals employ a subtractive rule where a smaller symbol placed before a larger one reduces the total (e.g., “IV” equals 4). The implementation detects these patterns by comparing c with prev. When a subtractive pair is identified, the code adds the larger value and simultaneously subtracts twice the smaller value that was previously added. This technique eliminates the need for a separate subtraction step.
case 'V': if (prev == 'I') result += 5-2*1; else result += 5; break;
case 'X': if (prev == 'I') result += 10-2*1; else result += 10; break;
case 'L': if (prev == 'X') result += 50-2*10; else result += 50; break;
case 'C': if (prev == 'X') result += 100-2*10; else result += 100; break;
case 'D': if (prev == 'C') result += 500-2*100; else result += 500; break;
case 'M': if (prev == 'C') result += 1000-2*100; else result += 1000; break;
For a pair such as “IV”, the first iteration adds 1 for ‘I’. When ‘V’ is processed, prev equals ‘I’, triggering the expression 5-2*1, which effectively adds 3, yielding a total of 4. The same principle applies to all other subtractive combinations (IX, XL, XC, CD, CM).
Edge Cases Covered
The algorithm naturally handles repeated symbols because each occurrence contributes its base value independently; for example, “III” results in three successive additions of 1. It also correctly processes a subtractive pair that appears at the start of the string, as the first character sets prev and the second character’s case logic adjusts the total accordingly. Mixed sequences that combine additive and subtractive patterns (e.g., “MCMXCIV”) are resolved step by step, with each character’s contribution determined by the immediate predecessor.
Performance Characteristics
The conversion runs in a single linear pass over the input, performing a constant amount of work per character. The use of a switch statement enables the compiler to generate an efficient jump table or branch sequence, minimizing dispatch overhead. No auxiliary containers or recursive calls are introduced, keeping the memory footprint minimal. Arithmetic adjustments for subtractive cases are performed inline, avoiding extra conditional branches or look-up structures. Consequently, the routine exhibits fast execution even for the longest valid Roman-numeral strings.
ELI5 - Simplified Explanation
Imagine you have a big treasure chest and you are counting special gold coins that have secret letters written on them instead of regular numbers. This code acts like a helper who looks at each coin in your pile one by one to figure out how much they are worth.
The helper starts with an empty bag and looks at the first letter. If the letter is an I, it means you have one coin, so the helper adds it to the bag. Other letters like V, X, L, C, D, or M represent bigger piles of coins.
Sometimes, the letters are tricky. If you see a small letter before a big letter, it is like a little game where you have to subtract the value of the small letter instead of adding it. The helper keeps track of the letter it just saw so it knows if it needs to do this special trick. For example, if it sees an I followed by a V, it realizes you are holding a four, so it does the math to make sure the count stays exactly right. It does this work over and over until every single coin in the pile has been counted and added together to find the final total.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
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 | JS | Ruby | Go | PHP | TS | |||
| LeetcodeHelp | C++ | Python | Java | |||||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||||
| Progiez | C++ | Python | Java | |||||||||||
| github | AdelDaniel | Dart | ||||||||||||
| aylei | Rust | |||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++ | |||||||||||||
| bujosa | Rust | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| DimitrisJim | C | |||||||||||||
| everthis | JS | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | C# | |||||||||||||
| fengvyi | C++ | |||||||||||||
| fpdjsns | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| gouthampradhan | Java | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JS | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| Krazune | C++ | |||||||||||||
| lennylxx | C | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| MacJim | C++ | |||||||||||||
| martianoff | Scala | |||||||||||||
| pruthvikp | Python | |||||||||||||
| 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, JavaScript, PHP, Python, Ruby, Rust, TypeScript | |||||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||||
| Progiez | C++, Java, Python | |||||||||||||
| AdelDaniel | Dart | |||||||||||||
| aylei | Rust | |||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++, C++ | |||||||||||||
| bujosa | Rust | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| DimitrisJim | C | |||||||||||||
| everthis | JavaScript | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | C# | |||||||||||||
| fengvyi | C++ | |||||||||||||
| fpdjsns | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| gouthampradhan | Java | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JavaScript | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| Krazune | C++ | |||||||||||||
| lennylxx | C | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| MacJim | C++ | |||||||||||||
| martianoff | Scala | |||||||||||||
| pruthvikp | Python | |||||||||||||
| 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 12: Integer to Roman
Solved On The Same Day
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
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