13. Roman to Integer
LeetCode 13. Roman to Integer
Description
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II
in Roman numeral, just two one’s added together. Twelve is written as, XII
, which is simply X
+ II
. The number twenty seven is written as XXVII
, which is XX
+ V
+ II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Tags
Math, String
Solution
遍历字符串,先检查连续的两个字符是否存在映射,如果存在则将相应的数字累加在结果上,如果不存在或者已经遍历到最后一个字符,则将当前这一个字符映射的数字累加在结果上,最后返回结果。
Before start, collate all mapping from symbol to value. Traverse the string and check if there is a mapping for the current 2 consecutive characters first. If it exists, the corresponding number is added to the result. Otherwise the single-character symbol corresponded value is accumulated on the result.
Complexity
Time complexity:
Space complexity:
Code
func romanToInt(s string) int {
var ans int
for i := 0; i < len(s); i++ {
var singleFlag bool
if i+1 < len(s) {
switch s[i : i+2] {
case "IV":
ans += 4
i++
case "IX":
ans += 9
i++
case "XL":
ans += 40
i++
case "XC":
ans += 90
i++
case "CD":
ans += 400
i++
case "CM":
ans += 900
i++
default:
singleFlag = true
}
} else {
singleFlag = true
}
if singleFlag {
switch s[i] {
case 'I':
ans += 1
case 'V':
ans += 5
case 'X':
ans += 10
case 'L':
ans += 50
case 'C':
ans += 100
case 'D':
ans += 500
case 'M':
ans += 1000
}
}
}
return ans
}
Last updated
Was this helpful?