Leetcode 12,13. Interger to Roman, Roman to Integer

 1 class Solution(object):
 2     def intToRoman(self, num):
 3         """
 4         :type num: int
 5         :rtype: str
 6         """
 7         rom = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
 8         
 9         ans = []
10         p = num/1000
11         ans += ['M']*p
12         num = num%1000
13         
14         p = num/100
15         if p <= 3:
16             ans += ['C']*p
17         elif p == 4:
18             ans += ['CD']
19         elif 5<= p <= 8 :
20             ans += ['D']+['C']*(p-5)
21         elif p == 9:
22             ans += ['CM']
23         num = num%100
24         
25         p = num/10
26         if p <= 3:
27             ans += ['X']*p
28         elif p == 4:
29             ans += ['XL']
30         elif 5 <= p <=8 :
31             ans += ['L']+['X']*(p-5)
32         elif p == 9:
33             ans += ['XC']
34         num = num%10
35         
36         p = num
37         if p <= 3:
38             ans += ['I']*p
39         elif p == 4:
40             ans += ['IV']
41         elif 5 <= p <= 8:
42             ans += ['V']+['I']*(p-5)
43         elif p == 9:
44             ans += ['IX']
45         return ''.join(ans)
46         

 

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

 

思路:先建立一个对应的dict。注意转换规则中的特例,比如XL (=50-10), IV (=5-1), 也就是说当前的字母如果小于后面的那个,当前这个字母对应的数字取负。

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

 

转载于:https://www.cnblogs.com/lettuan/p/6443465.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值