Skip to content

Create solution2.py to 013.Roman to Integer, 80ms #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 20, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions solution/013.Roman to Integer/Solution2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Solution(object):
def romanToInt(self, s):
dict = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1} #对应关系存在一个字典里
sum = 0
for i in range(len(s)-1):
if dict[s[i]] < dict[s[i+1]]: #这里小于是因为只会有一个减的存在,换句话说如果两个一样的出现,应该是加法
sum -= dict[s[i]]
else:
sum += dict[s[i]]
return sum+dict[s[-1]] #最后一位一定是加