I've been trying to attempt some leetcode questions as a complete beginner, and a section requires me to convert/return the thousands, hundreds, tens and units place of a number.
This is the code in python.
class Solution:
def intToRoman(self, num: int) -> str:
list = {1 : 'I',
4 : 'IV',
5 : 'V',
9 : 'IX',
10: 'X',
40: 'XL',
50: 'L',
90: 'XC',
100: 'C',
400: 'CD',
500: 'D',
900: 'CM',
1000: 'M'}
thousands, hundreds, tens, unit = 0,0,0,0
string = ""
number = int(num)
#A Thousandth number
if number >= 1000:
thousands = number - (number % 1000) # 3549 - (3549 % 1000) = 3000
hundreds = number - thousands; #// 3549 - 3000 = 549
tens = hundreds % 100 #// 549 % 100 = 49
hundreds = hundreds - (hundreds % 100) #// 549 - (549 % 100) = 500
units = tens % 10
tens = tens - (tens % 10) #// 49 - (49 % 10) = 49 - 9 = 9
thou = thousands // 1000 # 3
#THOUSANDS
for i in range(thou):
string = string + (list[1000])
#HUNDREDS
hund = hundreds // 100
if hund < 4:
string = string +(hund * list[100])
elif hund == 4:
string = string +(list[400])
elif hund == 5:
string = string +(list[500])
elif hund >= 6 and hund <= 8:
string = string +(list[500])
hund = hund - 5
string = string +(hund * list[100])
elif hund == 9:
string = string +(list[900])
#TENS
ten = tens // 10
if ten < 4:
string = string +(ten * list[10])
elif ten == 4:
string = string +(list[40])
elif ten == 5:
string = string +(list[50])
elif ten >= 6 and ten <= 8:
string = string +(list[50])
ten = ten - 5
string = string +(ten * list[10])
elif ten == 9:
string = string +(list[90])
#UNITS
if unit < 4:
string = string +(unit * list[1])
elif unit == 5:
string = string +(list[5])
elif unit >= 6 and unit <= 8:
string = string +(list[5])
unit = unit - 5
string = string +(unit * list[1])
elif unit == 9:
string = string +(list[9])
return string
Now, my problem is that the Units variable is holding zero. I can't figure out why? This exact block of code when translated to C works properly. Is there something funky about Mod in python that I'm missing?
Ex: If the input number is 3549 (Integer has to be converted into a roman numeral), the units variable holds zero. The output should be MMMDXLIX.
Since IX in the output depends on the units variable (which holds zero for some reason), the output is MMMDXL
Btw the function only works on a number >= 1000. I've not coded any further.