Roman to Integer

I solved this using Java before so this is just a re-implementation in Kotlin language.

class Solution {
    fun romanToInt(s: String): Int {
        var output = 0
        var prev = '0'
        for(index in s.indices){
            var c = s[index]
            if(index > 0){
                prev = s[index - 1]
            }
            
            when {
                c == 'I' -> output += 1
                c == 'V' -> output += 5
                c == 'X' -> output += 10
                c == 'L' -> output += 50
                c == 'C' -> output += 100
                c == 'D' -> output += 500
                c == 'M' -> output += 1000
            }
            
            when {
                (c == 'V' || c == 'X') && prev == 'I' -> output -= 2
                (c == 'L' || c == 'C') && prev == 'X' -> output -= 20
                (c == 'D' || c == 'M') && prev == 'C' -> output -= 200
            }
        }
        
        return output
    }
}
Runtime: 196 ms, faster than 83.02% of Kotlin online submissions for Roman to Integer.
Memory Usage: 34.9 MB, less than 100.00% of Kotlin online submissions for Roman to Integer.
comments powered by Disqus