题目来源:

https://leetcode.com/problems/roman-to-integer/


 

题意分析:

        这道题目和上一题目相反,是将罗马数字转化成阿拉伯数字。


 

题目思路:

       只要知道罗马数字和阿拉伯数字之间是怎么转换的就可以了。先做一个字符和数值对应的字典,{'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000};如果发现输入的字符串后一位比前一位小,则是出现4,9之类的,那么将前一个字符对应的数值减去两次就可以了。


 

代码(python):

 

 1 class Solution(object):
 2     def romanToInt(self, s):
 3         """
 4         :type s: str
 5         :rtype: int
 6         """
 7         d = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
 8         ans = 0
 9         size = len(s)
10         i = 0
11         while i < size:
12             if i > 0 and d[s[i]] > d[s[i - 1]]:
13                 ans += d[s[i]] - 2 * d[s[i - 1]]
14             else:
15                 ans += d[s[i]]
16             i += 1
17         return ans
View Code

相关文章:

  • 2021-11-04
  • 2021-07-24
  • 2021-10-04
  • 2021-10-29
  • 2022-02-15
  • 2021-07-08
  • 2021-07-19
  • 2022-12-23
猜你喜欢
  • 2021-04-12
  • 2021-12-10
  • 2021-08-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-31
相关资源
相似解决方案