Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

Roman to Integer Conversion in DSA Javascript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Roman to Integer Conversion
Start with input Roman string
↓
Initialize total = 0, index = 0
↓
Check current and next Roman chars
↓
If current < next: subtract current from total
↓
Else: add current to total
↓
Move index forward
↓
Repeat until end of string
↓
Return total as integer
We scan the Roman string left to right, adding or subtracting values based on the next character, then return the total integer.
Execution Sample
DSA Javascript
function romanToInt(s) {
  const map = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000};
  let total = 0, i = 0;
  while (i < s.length) {
    if (map[s[i]] < map[s[i+1]]) total -= map[s[i]];
    else total += map[s[i]];
    i++;
  }
  return total;
}
This code converts a Roman numeral string to an integer by scanning characters and adding or subtracting values.
Execution Table
StepOperationCurrent CharNext CharCondition (current < next)ActionTotal After ActionIndex After ActionVisual State
1InitializeN/AN/AN/Atotal=0, i=000total=0, i=0
2Check charsMC1000 < 100? FalseAdd 100010001total=1000, i=1
3Check charsCM100 < 1000? TrueSubtract 1009002total=900, i=2
4Check charsMX1000 < 10? FalseAdd 100019003total=1900, i=3
5Check charsXI10 < 1? FalseAdd 1019104total=1910, i=4
6Check charsIV1 < 5? TrueSubtract 119095total=1909, i=5
7Check charsVN/A5 < undefined? FalseAdd 519146total=1914, i=6
8EndN/AN/Ai == s.lengthReturn total19146Final total=1914
💡 Index i reaches string length, loop ends and total is returned.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6After Step 7Final
total0100090019001910190919141914
i01234566
Key Moments - 3 Insights
Why do we subtract the current value when it is less than the next?
Because in Roman numerals, a smaller value before a larger one means subtraction (see steps 3 and 6 in execution_table where 'C' before 'M' and 'I' before 'V' cause subtraction).
What happens when the current character is the last one in the string?
Since there is no next character, the condition current < next is false (next is undefined), so we add the current value (see step 7).
Why do we increment the index by 1 each time instead of 2 when subtracting?
Because each character is processed one by one; subtraction is handled by adding negative value, so index moves forward by 1 each step (see index changes in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the total after step 3?
A1000
B900
C1900
D1910
💡 Hint
Check the 'Total After Action' column at step 3 in execution_table.
At which step does the condition current < next become true for the first time?
AStep 2
BStep 3
CStep 5
DStep 6
💡 Hint
Look at the 'Condition (current < next)' column in execution_table to find the first 'True'.
If the input was 'III', how would the total change after step 3 compared to the current example?
AIt would be 3
BIt would be 2
CIt would be 1
DIt would be 0
💡 Hint
Consider that 'I' is always added since next is never larger in 'III'; check variable_tracker for total changes.
Concept Snapshot
Roman to Integer Conversion:
- Map Roman chars to values.
- Scan string left to right.
- If current < next, subtract current.
- Else, add current.
- Move index by 1 each step.
- Return total at end.
Full Transcript
This visualization shows how to convert a Roman numeral string to an integer by scanning each character from left to right. We keep a total starting at zero and an index starting at zero. At each step, we compare the current Roman character's value with the next character's value. If the current is less than the next, we subtract its value from the total; otherwise, we add it. We then move the index forward by one and repeat until we reach the end of the string. The final total is the integer value of the Roman numeral. Key moments include understanding why subtraction happens when a smaller value precedes a larger one, how the last character is handled, and why the index increments by one each time. The execution table traces these steps with a sample input 'MCMXIV' resulting in 1914.

Practice

(1/5)
1. What is the main rule to convert Roman numerals to integers?
easy
A. Subtract all values from the largest symbol
B. Add values of symbols, subtract if a smaller symbol is before a larger one
C. Add values only if symbols are the same
D. Multiply values of symbols in order

Solution

  1. Step 1: Understand Roman numeral rules

    Roman numerals are added normally, but if a smaller numeral appears before a larger one, it is subtracted.
  2. Step 2: Apply addition and subtraction rules

    For example, IV is 5 - 1 = 4, while VI is 5 + 1 = 6.
  3. Final Answer:

    Add values of symbols, subtract if a smaller symbol is before a larger one -> Option B
  4. Quick Check:

    Roman numeral rules = Add and subtract [OK]
Hint: Subtract when smaller numeral precedes larger one [OK]
Common Mistakes:
  • Always adding without subtraction
  • Multiplying values incorrectly
  • Ignoring order of symbols
2. Which of the following is the correct JavaScript syntax to get the integer value of a Roman numeral character from a map object named romanMap?
easy
A. romanMap['V']
B. romanMap.get('V')
C. romanMap.V
D. romanMap('V')

Solution

  1. Step 1: Identify the data structure type

    If romanMap is a plain JavaScript object, access values using square brackets with the key as a string.
  2. Step 2: Choose correct syntax for object property access

    Using romanMap['V'] correctly accesses the value for key 'V'. romanMap.get('V') is for Map objects, not plain objects.
  3. Final Answer:

    romanMap['V'] -> Option A
  4. Quick Check:

    Object property access = romanMap['V'] [OK]
Hint: Use square brackets for object keys as strings [OK]
Common Mistakes:
  • Using .get() on plain objects
  • Using dot notation with string keys
  • Calling object like a function
3. What will be the output of the following JavaScript code?
function romanToInt(s) {
  const map = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000};
  let total = 0;
  for(let i = 0; i < s.length; i++) {
    const current = map[s[i]];
    const next = map[s[i+1]] || 0;
    if(current < next) {
      total -= current;
    } else {
      total += current;
    }
  }
  return total;
}
console.log(romanToInt('IX'));
medium
A. 9
B. 11
C. 1
D. Error

Solution

  1. Step 1: Trace the loop for input 'IX'

    For 'I' (1), next is 'X' (10), since 1 < 10, subtract 1 (total = -1). For 'X' (10), next is undefined (0), so add 10 (total = 9).
  2. Step 2: Calculate final total

    Total after loop is 9, which is the integer value of 'IX'.
  3. Final Answer:

    9 -> Option A
  4. Quick Check:

    'IX' = 9 [OK]
Hint: Subtract if current < next, else add [OK]
Common Mistakes:
  • Adding all values without subtraction
  • Ignoring next character check
  • Off-by-one errors in loop
4. Find the error in this JavaScript function for Roman to Integer conversion:
function romanToInt(s) {
  const map = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000};
  let total = 0;
  for(let i = 0; i <= s.length; i++) {
    const current = map[s[i]];
    const next = map[s[i+1]] || 0;
    if(current < next) {
      total -= current;
    } else {
      total += current;
    }
  }
  return total;
}
medium
A. Use '==' instead of '<' in if condition
B. map object keys should be lowercase
C. total should be initialized to 1
D. Loop condition should be i < s.length, not i <= s.length

Solution

  1. Step 1: Analyze loop boundary

    The loop runs from i = 0 to i <= s.length, which means it accesses s[s.length], an undefined index causing current to be undefined.
  2. Step 2: Correct loop condition

    Changing loop condition to i < s.length prevents accessing out-of-bound index and avoids errors.
  3. Final Answer:

    Loop condition should be i < s.length, not i <= s.length -> Option D
  4. Quick Check:

    Loop boundary off-by-one error fixed [OK]
Hint: Use i < length to avoid out-of-bound errors [OK]
Common Mistakes:
  • Using <= instead of < in loops
  • Wrong case for map keys
  • Incorrect comparison operators
5. Given the Roman numeral string 'MCMXCIV', what integer should the conversion function return?
hard
A. 2004
B. 1904
C. 1994
D. 1094

Solution

  1. Step 1: Break down the Roman numeral 'MCMXCIV'

    M = 1000, CM = 900 (1000 - 100), XC = 90 (100 - 10), IV = 4 (5 - 1).
  2. Step 2: Add all parts

    1000 + 900 + 90 + 4 = 1994 total.
  3. Final Answer:

    1994 -> Option C
  4. Quick Check:

    'MCMXCIV' = 1994 [OK]
Hint: Identify subtractive pairs and sum all values [OK]
Common Mistakes:
  • Adding all numerals without subtraction
  • Misreading subtractive pairs
  • Confusing similar numerals
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard