題目
原題鏈接
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路
TODO:之后添加
代碼
class Solution {
/**
/// @brief: 規(guī)則如下
/// I(1)礁苗,V(5)井誉,X(10),L(50)记劈,C(100)决瞳,D(500)抵皱,M(1000)
/// 右加左減
/// 在一個較大的羅馬數(shù)字的右邊記上一個較小的羅馬數(shù)字,表示大數(shù)字加小數(shù)字个绍。
/// 在一個較大的數(shù)字的左邊記上1個較小的羅馬數(shù)字技健,表示大數(shù)字減小數(shù)字
*/
func romanToInt(s: String) -> Int {
var result :Int = 0
var currIndex = s.endIndex
var currValue = 0 // 注意result = 0 其實看成了加上currValue的結果
while(currIndex != s.startIndex){
let prevIndex = currIndex.predecessor()
let prevValue = romanMapInt(s[prevIndex])
if(prevValue >= currValue){
result += prevValue
}else{
result -= prevValue
}
currIndex = prevIndex
currValue = prevValue
}
return result
}
func romanMapInt(c:Character)->Int{
switch(c) {
case "I": return 1;
case "V": return 5;
case "X": return 10;
case "L": return 50;
case "C": return 100;
case "D": return 500;
case "M": return 1000;
default: return 0;
}
}
}