Skip to content

Commit 4612eeb

Browse files
committed
Adding Simple Solution - Problem - 13 - Roman Integer
1 parent 880d092 commit 4612eeb

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Roman_Integer/SimpleSolution.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 13
6+
## Problem Name: Roman to Integer
7+
##===================================
8+
#
9+
#Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
10+
#
11+
#Symbol Value
12+
#I 1
13+
#V 5
14+
#X 10
15+
#L 50
16+
#C 100
17+
#D 500
18+
#M 1000
19+
#For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
20+
#
21+
#Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
22+
#
23+
#I can be placed before V (5) and X (10) to make 4 and 9.
24+
#X can be placed before L (50) and C (100) to make 40 and 90.
25+
#C can be placed before D (500) and M (1000) to make 400 and 900.
26+
#Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
27+
#
28+
#Example 1:
29+
#
30+
#Input: "III"
31+
#Output: 3
32+
#Example 2:
33+
#
34+
#Input: "IV"
35+
#Output: 4
36+
#Example 3:
37+
#
38+
#Input: "IX"
39+
#Output: 9
40+
#Example 4:
41+
#
42+
#Input: "LVIII"
43+
#Output: 58
44+
#Explanation: L = 50, V= 5, III = 3.
45+
#Example 5:
46+
#
47+
#Input: "MCMXCIV"
48+
#Output: 1994
49+
#Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
50+
class Solution:
51+
def romanToInt(self, s):
52+
dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} #Initialize dictionary and store values key, value
53+
sum, current, previous = 0, 0, 0 #Initialize sum, current and previous
54+
for i in range(len(s)): #Loop through string
55+
current = dict[s[i]] #Update current by dictionary's first key, value
56+
if current > previous: #Condition-check: If current is greater than previous
57+
sum = sum + current - 2 * previous #Update sum
58+
else: #Condition-check: Else
59+
sum += current #Update sum
60+
return sum

0 commit comments

Comments
 (0)