https://leetcode.com/problems/roman-to-integer/description/
将罗马数字转换为阿拉伯数字,需要考虑几种特殊情况,比如 IV 代表4
思路:
所有特殊情况字母的和是6或11的倍数。那么只需要判断上一个字符和当前字符的和满不满足这个条件,且要满足上一个字符对应数字<当前字符。
class Solution {
fun romanToInt(s: String): Int {
val map = hashMapOf('I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100,'D' to 500, 'M' to 1000)
var result = 0
var lastValue = 0
s.forEach{i->
val value = map.get(i)?:0
val temp = lastValue + value
if(lastValue < value) {
if(temp%6 == 0){
result -= 2*temp/6
}else if(temp%11==0){
result -= 2*temp/11
}
}
result += value
lastValue = value
}
return result
}
}
fun main(args: Array<String>) {
val res = Solution().romanToInt("MCMXCIV")
println("result=$res")
}
提交完看了下解析,考虑复杂了,有更简单的做法 。
思路:
不考虑特殊情况下,所有的字符从左到右都是符合从大到小的规律。特殊情况下只要不符合这个规律的数字,减去当前数字就行了。
class Solution {
fun romanToInt(s: String): Int {
val map = hashMapOf('I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100,'D' to 500, 'M' to 1000)
var result = 0
var lastValue = 0
s.forEach{i->
val value = map.get(i)?:0
if(lastValue < value) {
result -= 2*lastValue
}
result += value
lastValue = value
}
return result
}
}
fun main(args: Array<String>) {
val res = Solution().romanToInt("MCMXCIV")
println("result=$res")
}
网友评论