我正在學習 Kotlin,在解決 leetcode 問題時遇到了問題。一些測驗用例值回傳預期的輸出,但是當我輸入"MCMXCIV"相當于1994時,我得到的輸出為 1990。誰能向我解釋我錯在哪里?提前致謝。
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
}
}
uj5u.com熱心網友回復:
total這里的問題是,如果情況并非如此,您將回傳s1<s2。即使你發現了一個這樣的情況,那不是字串的結尾,你應該繼續處理。而不是回傳,你應該遞增i到i 2你已經處理過i 1的。由于您不能在 for 回圈之間進行這種增量,因此您將不得不使用 while 回圈。
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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/505248.html
