A*******e 发帖数: 2419 | 1 怎么觉得有二义性呢?
MCMXCVI,按结果是M+(C-M)+(C-X)+(V+I) = 1996,为何不是(M+C) +(M+X) + (C+V)+I
= 2216?左减优先? | A*******e 发帖数: 2419 | 2 百度百科的规则,没有排除二义性。
http://baike.baidu.com/view/42061.htm
I
【在 A*******e 的大作中提到】 : 怎么觉得有二义性呢? : MCMXCVI,按结果是M+(C-M)+(C-X)+(V+I) = 1996,为何不是(M+C) +(M+X) + (C+V)+I : = 2216?左减优先?
| t********5 发帖数: 522 | 3 应该是只要左边比右边大,就要相减。建议看wiki的规则,非常清楚明了 | A*******e 发帖数: 2419 | 4 明白了。中文版说的不清楚,还得看英文维基。
没有右加规则,只有左减,仅限于I,X,C
【在 A*******e 的大作中提到】 : 百度百科的规则,没有排除二义性。 : http://baike.baidu.com/view/42061.htm : : I
| A*******e 发帖数: 2419 | 5 说反了,是左小右大。而且这个总结也不准确,是以下具体三条规则:
1. I placed before V or X indicates one less, so four is IV (one less than
five) and nine is IX (one less than ten)
2. X placed before L or C indicates ten less, so forty is XL (ten less than
fifty) and ninety is XC (ten less than a hundred)
3. C placed before D or M indicates a hundred less, so four hundred is CD (a
hundred less than five hundred) and nine hundred is CM (a hundred less than
a thousand)[5]
【在 t********5 的大作中提到】 : 应该是只要左边比右边大,就要相减。建议看wiki的规则,非常清楚明了
| t********5 发帖数: 522 | 6 哈哈 翻了一下LC,原来我是hardcode的,应该更简洁一些
其实应该用一个index i的,我比较懒直接修改了原string,面试想修改原string的同
学最好征求面试官的意见
class Solution:
# @param s, a string
# @return an integer
def romanToInt(self, s):
ROMAN_INT = {'M': 1000, 'CM': 900, 'D': 500, 'CD': 400,
'C': 100, 'XC': 90, 'L': 50, 'XL': 40,
'X': 10, 'IX': 9, 'V': 5, 'IV': 4, 'I': 1}
result = 0
while s:
if s[:2] in ROMAN_INT:
result += ROMAN_INT[s[:2]]
s = s[2:]
elif s[:1] in ROMAN_INT:
result += ROMAN_INT[s[:1]]
s = s[1:]
else:
return -1
return result
than
(a
than
【在 A*******e 的大作中提到】 : 说反了,是左小右大。而且这个总结也不准确,是以下具体三条规则: : 1. I placed before V or X indicates one less, so four is IV (one less than : five) and nine is IX (one less than ten) : 2. X placed before L or C indicates ten less, so forty is XL (ten less than : fifty) and ninety is XC (ten less than a hundred) : 3. C placed before D or M indicates a hundred less, so four hundred is CD (a : hundred less than five hundred) and nine hundred is CM (a hundred less than : a thousand)[5]
|
|