[Swift LeetCode]13. Roman to Integer
題目
原題連結
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: 規則如下
/// I(1),V(5),X(10),L(50),C(100),D(500),M(1000)
/// 右加左減
/// 在一個較大的羅馬數字的右邊記上一個較小的羅馬數字,表示大數字加小數字。
/// 在一個較大的數字的左邊記上1個較小的羅馬數字,表示大數字減小數字
*/
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;
}
}
}
相關文章
- 13. Roman to Integer--LeetCode RecordLeetCode
- LeetCode 13. Roman to Integer C語言LeetCodeC語言
- Leetcode Integer to RomanLeetCode
- leetcode Roman to IntegerLeetCode
- [LeetCode] Roman to IntegerLeetCode
- Leetcode 12 Integer to RomanLeetCode
- Leetcode 13 Roman to IntegerLeetCode
- Leetcode-Roman to IntegerLeetCode
- Leetcode-Integer to RomanLeetCode
- Integer to Roman leetcode javaLeetCodeJava
- Roman to Integer leetcode javaLeetCodeJava
- Leetcode 12. Integer to RomanLeetCode
- LeetCode Roman to Integer(013)解法總結LeetCode
- LeetCode - 解題筆記 - 12 - Integer to RomanLeetCode筆記
- LeetCode Integer to Roman(012)解法總結LeetCode
- [LeetCode] Integer to Roman 整數轉化成羅馬數字LeetCode
- [LeetCode] Roman to Integer 羅馬數字轉化成整數LeetCode
- leetcode Reverse IntegerLeetCode
- Leetcode 7 Reverse IntegerLeetCode
- LeetCode-Integer ReplacementLeetCode
- LeetCode-Integer BreaksLeetCode
- Reverse Integer leetcode javaLeetCodeJava
- Leetcode 273 Integer to English WordsLeetCode
- Leetcode-Problem:Reverse IntegerLeetCode
- LeetCode-Integer to English WordsLeetCode
- leetcode String to Integer (atoi)LeetCode
- Leetcode - String to Integer (atoi)LeetCode
- Leetcode 8 String to Integer (atoi)LeetCode
- LeetCode 第 7 題(Reverse Integer)LeetCode
- LeetCode 第 343 題 (Integer Break)LeetCode
- String to Integer (atoi) leetcode javaLeetCodeJava
- [leetcode] 1394. Find Lucky Integer in an ArrayLeetCode
- [LeetCode] Reverse Integer 翻轉整數LeetCode
- LeetCode Reverse Integer(007)解法總結LeetCode
- LeetCode - 解題筆記 - 7 - Reverse IntegerLeetCode筆記
- 【LeetCode從零單排】No.7 Reverse IntegerLeetCode
- LeetCode String to Integer (atoi)(008)解法總結LeetCode
- [LeetCode] String to Integer (atoi) 字串轉為整數LeetCode字串