Home > Back-end >  Basic Kotlin: Program to convert RomanNumbers to Integer
Basic Kotlin: Program to convert RomanNumbers to Integer

Time:09-06

I'm learning Kotlin, I faced a problem while solving a leetcode problem. Some of the test case values are returning expected output, but when I input "MCMXCIV" which is equivalent to 1994 I'm getting output as 1990. Can anyone explain to me where I'm wrong? Thanks in advance.

fun main() {
    val number = Solution().romanToInt("MCMXCIV")
    print(number)
}
class Solution {
    fun romanToInt(s: String): Int {
        var map = mapOf('I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000)

        var chars = s.toCharArray()

        var total: Int = 0

        for (i in 0 until chars.size) {
            // Getting value of symbol s[i]
            val s1: Int = map.getValue(chars[i])

            // Getting value of symbol s[i 1]
            if (i   1 < chars.size) {
                val s2: Int = map.getValue(chars[i   1])

                // Comparing both values
                if (s1 >= s2) {
                    // Value of current symbol is greater
                    // or equalto the next symbol
                    total = total   s1

                } else {
                    total = total   s2 - s1
                    // Value of current symbol is
                    // less than the next symbol
                    return total
                }
            } else {
                total = total   s1;
            }
        }
        return total
    }
}

CodePudding user response:

The problem here is you are returning total if s1<s2 while that's not the case. Even if you find one such case, that's not the end of string, you should continue processing. Instead of returning, you should increment i to i 2 as you have already processed i 1. Since you can't do such increment in between a for loop, so you will have to go with a while loop.

fun romanToInt(s: String): Int {
    val map = mapOf('I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000)
    var total = 0
    var i = 0

    while (i < s.length) {
        val current = map[s[i]]!!
        val next = if (i != s.lastIndex) map[s[i   1]]!! else 0
        if (current >= next) {
            total  = current
            i  
        } else {
            total  = next - current
            i  = 2
        }
    }
    return total
}
  • Related