Roman to Integer
题目:难度(Easy)
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Tags: Math, String
分析:罗马数字共有七个,即I(1),V(5),X(10),L(50),C(100),D(500),M(1000)。
按照下面的规则可以表示任意正整数。
1.重复数次:一个罗马数字重复几次,就表示这个数的几倍。
2.右加左减:在一个较大的罗马数字的右边记上一个较小的罗马数字,表示大数字加小数字。在一个较大的数字的左边记上一个较小的罗马数字,表示大数字减小数字。但是,左减不能跨越等级。比如,99不可以用IC表示,用XCIX表示。
3.加线乘千:在一个罗马数字的上方加上一条横线或者在右下方写M,表示将这个数字乘以1000,即是原数的1000倍。同理,如果上方有两条横线,即是原数的1000000倍。
4.单位限制:同样单位只能出现3次,如40不能表示为XXXX,而要表示为XL。
代码实现:
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
分析:如果检测到当前字符后面的字符对应的值比他大,那么当前字符就是负的
"""
n = len(s)
if n == 0:
return 0
hash = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
result = 0
for i in range(n-1):
if hash[s[i+1]]>hash[s[i]]:
result -= hash[s[i]]
else:
result += hash[s[i]]
result += hash[s[-1]]#还剩下最后一个字符没有解码
return result
Integer to Roman
题目:难度(Medium)
Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.
Tags: Math, String
分析:不同的数字对应不同的罗马字符,将数字从“高位”逐步计算到“低位”。
代码实现:
class Solution(object):
def intToRoman(self, num):
nums = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
romans = ["I","IV","V","IX","X","XL","L","XC","C","CD","D", "CM","M"]
result = []
for i in range(len(nums)-1, -1, -1):
if num >= nums[i]:
div, mod = divmod(num, nums[i])#返回商,余数
result.append(romans[i]*div)
num = mod
return "".join(result)