·
·
文章目录
  1. 题目介绍
  2. 解题思路

Roman to Integer

题目介绍

LeetCode 13. Roman to Integer,题目的意思将罗马数字转换为对应的整数,范围 1~3999。

解题思路

首先肯定先了解下罗马数字的构成规则:

字符 I V X L C D M
数字 1 5 10 50 100 500 1000
  1. 相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
  2. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
  3. 小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
  4. 正常使用时,连写的数字重复不得超过三次。

思路很简单,从低位向高位按位转换成整数进行加减。因为不存在违规的罗马数字,所以高位比低位低的则为减,否则则为加。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
func romanToInt(_ s: String) -> Int {
var pre = Int.min
var sum = 0
for character in s.reversed() {
let int = toInt(character)
if int < pre {
sum -= int
} else {
sum += int
}
pre = int
}
return sum
}

private func toInt(_ character: Character) -> Int {
switch character {
case "M":
return 1000
case "D":
return 500
case "C":
return 100
case "L":
return 50
case "X":
return 10
case "V":
return 5
case "I":
return 1
default:
return 0
}
}
}
**版权声明**

Ivan’s Blog by Ivan Ye is licensed under a Creative Commons BY-NC-ND 4.0 International License.
叶帆创作并维护的叶帆的博客博客采用创作共用保留署名-非商业-禁止演绎4.0国际许可证

本文首发于Ivan’s Blog | 叶帆的博客博客( http://yeziahehe.com ),版权所有,侵权必究。

本文链接:http://yeziahehe.com/2017/11/14/RomanToInteger/

支持一下
扫一扫,支持yeziahehe
  • 微信扫一扫
  • 支付宝扫一扫