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
.
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
Last updated
Was this helpful?