博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 12,13. Interger to Roman, Roman to Integer
阅读量:4559 次
发布时间:2019-06-08

本文共 1905 字,大约阅读时间需要 6 分钟。

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/100011 ans += ['M']*p12 num = num%100013 14 p = num/10015 if p <= 3:16 ans += ['C']*p17 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%10024 25 p = num/1026 if p <= 3:27 ans += ['X']*p28 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%1035 36 p = num37 if p <= 3:38 ans += ['I']*p39 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 = 012 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

你可能感兴趣的文章
VS2008无法切换到视图设计器
查看>>
爱情故事:追忆似水流年 回味永恒的爱恋
查看>>
android mvn android:deploy签名问题
查看>>
transient
查看>>
[HDU 4348]To the moon
查看>>
初识【Windows API】--文本去重
查看>>
[转]IOS多线程
查看>>
详解spl_autoload_register() 与 __autoload
查看>>
Axure RP Extension for Chrome安装
查看>>
day_10
查看>>
ArcGIS API for JavaScript 入门教程[6] 再讲数据——Map类之可操作图层
查看>>
tfs2012 的体验地址
查看>>
打造专业外观-九宫图
查看>>
让discuz论坛单独版块贴子侧边栏(用户信息栏)关闭的修改办法
查看>>
倒计时
查看>>
Robolectric
查看>>
搜索引擎之全文搜索算法功能实现(基于Lucene)
查看>>
XShell远程连接本地虚机
查看>>
好吧,又失眠
查看>>
一个不错的cv个人主页
查看>>