TryBugHunt
goLogic errorMedium

Roman numeral converter returns negative years

BugFind the bug and fix the code

What it should do

romanToInt(s) converts a Roman numeral to a number. A smaller symbol before a larger one is subtracted, so romanToInt("XIV") returns 14 and romanToInt("MCMXCIV") returns 1994.

What happens instead

romanToInt("XIV") returns -4, and romanToInt("MCMXCIV") returns -1984.

package main

func romanToInt(s string) int {
    values := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    total := 0
    for i := 0; i < len(s); i++ {
        v := values[s[i]]
        if i+1 < len(s) && v > values[s[i+1]] {
            total -= v
        } else {
            total += v
        }
    }
    return total
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the logic errors pattern

The wrong operator, an inverted condition, a formula the right way round but backwards.

What you'll practise

A medium Go debugging exercise about logic errors: the wrong operator, an inverted condition, a formula the right way round but backwards.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

In Roman numerals a symbol is subtracted only when a larger symbol follows it, as with the I in IV. The comparison is flipped, so the code subtracts symbols that are followed by a smaller one, which is the normal case, and adds the ones that should be subtracted. Numerals made of one repeated symbol, like III, still work because neither comparison is true. When a result has the right size but the wrong sign, look for a comparison pointing the wrong way.

The pattern behind it: logic errors.

More logic errors to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/9854c533-673a-4d91-9a64-dd4e280abc59" title="Debugging challenge: Roman numeral converter returns negative years" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/9854c533-673a-4d91-9a64-dd4e280abc59">TryBugHunt</a></p>