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