I have a homework problem. I need to write a function that receives a positive integer and a digit. This function removes all the digits as same is the given digit from the number.
Example for the function:
removeDigit(78452813, 8) => 745213 (removes all 8)
This is my code:
Code in text:
def removeDigit(num,digit):
temp=0
while num>0:
remDigit=num % 10
num=int(num / 10)
if remDigit != digit:
temp=temp * 10 + remDigit
else:
continue
return temp
My function deletes the digit, but it returns the new number reversed.
Does anyone knows how to fix this?
there are many ways to solve this problem, here is one: instead of
temp = temp * 10 + rem_digit
you can do
temp = temp / 10 + rem_digit
in this case the order is preserved.
now you just need to make it an integer again:
while not temp.is_integer():
temp *= 10
return int(temp)
Have you tried converting the number to a string and using string.replace()? I'm not going to do your homework for you but that should be a good place to start.
You could try a recursive approach:
def remDigit(N,S):
n,d = divmod(N,10)
return 0 if not N else remDigit(n,S) if d==S else remDigit(n,S)*10+d
r = remDigit(78452813, 8)
print(r)
745213
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.