Skip to content

Instantly share code, notes, and snippets.

@ahmedazhar05
Last active September 23, 2021 15:50
Show Gist options
  • Save ahmedazhar05/bb6a6478d9466e153b039985576ab28e to your computer and use it in GitHub Desktop.
Save ahmedazhar05/bb6a6478d9466e153b039985576ab28e to your computer and use it in GitHub Desktop.
Convert Decimal number to Roman and vice versa
def decToRoman(n):
dec = {
"1": "I",
"5": "V",
"10": "X",
"50": "L",
"100": "C",
"500": "D",
"1000": "M"
}
m = 1000
roman = ""
while n > 0 and m > 0:
x = n // m
c = dec[str(m)]
if x > 8:
roman = roman + c + dec[str(m * 10)]
elif x >= 5:
roman = roman + dec[str(m * 5)] + "".join([c * (x - 5)])
elif x > 3:
roman = roman + c + dec[str(m * 5)]
elif n >= m:
roman = roman + "".join([c * x])
n = n - m * x
m = m // 10
return roman
def romanToDec(s):
rom = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
dec = psum = 0
p = ''
for c in s:
if c == p:
psum = psum + rom[c]
elif psum > rom[c]:
dec = dec + psum
psum = rom[c]
elif psum < rom[c]:
psum = rom[c] - psum
p = c
return dec + psum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment