![](/img/trans.png)
[英]Specific digit occurence counter for a given integer from 0 to given integer in Python
[英]Remove digit from given integer
我有一个家庭作业问题。 我需要编写一个函数来接收一个正整数和一个数字。 此函数删除所有数字,因为数字中的给定数字相同。
函数示例:
removeDigit(78452813, 8) => 745213 (removes all 8)
这是我的代码:
文字代码:
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
我的函数删除了数字,但它返回了颠倒的新数字。
有谁知道如何解决这个问题?
有很多方法可以解决这个问题,这里是一个:而不是
temp = temp * 10 + rem_digit
你可以做
temp = temp / 10 + rem_digit
在这种情况下,订单被保留。
现在你只需要再次使它成为一个整数:
while not temp.is_integer():
temp *= 10
return int(temp)
您是否尝试过将数字转换为字符串并使用 string.replace()? 我不会为你做功课,但这应该是一个很好的起点。
您可以尝试递归方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.