[Swift] Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解法:
//兩兩拆開 從最後一個數開始看
//ex: XLV -> XL + V = 50-10 + 5 = 45
//XLIX -> XL + IX = 50-10 + 10-1 = 49
//拆開後兩兩相比 高位在前用加法 低位在前用減法
//XL = X 比 L 小 , 所以用減法 = ABS(10 - 50) = 40
//LX = 高位在前用加法 = L + X = 10 + 50
//LXXXIX = LX + XX + IX = 60 + 20 + ABS(1-10) = 89
----------------------------------------------
Input is guaranteed to be within the range from 1 to 3999.
解法:
//兩兩拆開 從最後一個數開始看
//ex: XLV -> XL + V = 50-10 + 5 = 45
//XLIX -> XL + IX = 50-10 + 10-1 = 49
//拆開後兩兩相比 高位在前用加法 低位在前用減法
//XL = X 比 L 小 , 所以用減法 = ABS(10 - 50) = 40
//LX = 高位在前用加法 = L + X = 10 + 50
//LXXXIX = LX + XX + IX = 60 + 20 + ABS(1-10) = 89
----------------------------------------------
class Solution {
func romanToInt(_ s: String) -> Int {
var dict = ["M":1000,"D":500,"C":100,"L":50,"X":10,"V":5,"I":1]
var ret = 0
var charAr = Array(s.characters)
while (charAr.count > 0) {
if (charAr.count >= 2){
let ch1 = dict[String(charAr[0])]
let ch2 = dict[String(charAr[1])]
if ch1! >= ch2! {
ret = ret + ch1!
//算完拿掉 避免重算
charAr.removeFirst()
}else{
ret = ret + abs(ch1! - ch2!)
charAr.removeFirst()
charAr.removeFirst()
}
}else{
//剩一個的情況
let ch1 = dict[String(charAr[0])]
ret = ret + ch1!
charAr.removeFirst()
}
}
return ret
}
}
func romanToInt(_ s: String) -> Int {
var dict = ["M":1000,"D":500,"C":100,"L":50,"X":10,"V":5,"I":1]
var ret = 0
var charAr = Array(s.characters)
while (charAr.count > 0) {
if (charAr.count >= 2){
let ch1 = dict[String(charAr[0])]
let ch2 = dict[String(charAr[1])]
if ch1! >= ch2! {
ret = ret + ch1!
//算完拿掉 避免重算
charAr.removeFirst()
}else{
ret = ret + abs(ch1! - ch2!)
charAr.removeFirst()
charAr.removeFirst()
}
}else{
//剩一個的情況
let ch1 = dict[String(charAr[0])]
ret = ret + ch1!
charAr.removeFirst()
}
}
return ret
}
}
0 comments: