leetcode 13 Roman to Integer
来源:互联网 发布:程序员有哪些方向 编辑:程序博客网 时间:2024/04/29 02:27
Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
从字符串中每次处理一位,处理前需要先找到剩余串的枢纽(剩余串中最大的),以判断当前值在其左边还是右边,该相加还是相减。import unittestfrom pprint import pprintimport pdbclass Solution: # @return an integer def romanToInt(self, s): dic={} dic["I"]=1 dic["V"]=5 dic["X"]=10 dic["L"]=50 dic["C"]=100 dic["D"]=500 dic["M"]=1000 lst=("I","V","X","L","C","D","M") num=0 for i in range(len(s)): for j in lst: if j in s[i:]: pivot=dic[j] #determin add or sub if dic[s[i]]>=pivot: num+=dic[s[i]] else: num-=dic[s[i]] return numclass testCase(unittest.TestCase): def setUp(self): pass self.a=Solution() def testLeet(self): self.assertEqual(self.a.romanToInt("I"),1) self.assertEqual(self.a.romanToInt("V"),5) self.assertEqual(self.a.romanToInt("X"),10) self.assertEqual(self.a.romanToInt("XXXIX"),39) self.assertEqual(self.a.romanToInt("CD"),400) self.assertEqual(self.a.romanToInt("MCM"),1900) self.assertEqual(self.a.romanToInt("MDCLXVI"),1666) self.assertEqual(self.a.romanToInt("MDCCCLXXXVIII"),1888) self.assertEqual(self.a.romanToInt("MCMLXXXIV"),1984)if __name__ == '__main__': unittest.main()
0 0
- leetcode-13:Roman to Integer
- leetcode 13 Roman to Integer
- Leetcode【13】:Roman to Integer
- [leetcode 13] Roman to Integer
- [Leetcode] 13 - Roman to Integer
- LeetCode | #13 Roman to Integer
- leetcode.13---------Roman to Integer
- leetCode #13 Roman to Integer
- leetcode-13 Roman to Integer
- leetcode 13 Roman to Integer
- LeetCode 13 Roman to Integer
- LeetCode 13 - Roman to Integer
- leetcode 13 -- Roman to Integer
- LeetCode 13:"Roman to Integer"
- LeetCode---(13)Roman to Integer
- leetcode-13Roman to Integer
- leetcode 13: Roman to Integer
- Leetcode 13 Roman to Integer
- anychart学习笔记之一javaScript中创建anychart
- xcode APP 打包以及提交apple审核详细流程
- whenever使用方法
- xcodebuild
- 转载--最简实例说明wait、notify、notifyAll的使用方法
- leetcode 13 Roman to Integer
- C++类对象内存模型与成员函数调用分析(中)
- 正则基础之 ?:
- 马踏棋盘--深度优先搜索
- 房贷计算公式
- C语言 小哼买书
- 创建者模式——建造者模式(Builder)(4)
- 教你如何迅速秒杀掉:99%的海量数据处理面试题
- HDU1331 HDU1579 Function Run Fun【记忆化搜索】