[英]Trying to figure out how many digits in a number are a multiple of another digit
我正在尝试编写一个 function ,它包含两个元素n
和m
,并将尝试给出n
中m
的倍数的数字计数。
例如,如果n = 650899, m = 3
,则答案为4
,因为数字{6, 0, 9, 9}
都可以被3
整除,而数字{5, 8}
则不能:
Calculation Cumulative count
---------------- ----------------
6 / 3 = 2 1
5 / 3 = 1.666...
0 / 3 = 0 2
8 / 3 = 2.666...
9 / 3 = 3 3
9 / 3 = 3 4 <- Answer
我试图在不使用字符串的情况下做到这一点(例如通过检查字符串中的单个字符)。 有谁知道我如何自己操纵数字?
尝试以下操作:
def solution(n: int, m: int) -> int:
"""
Check how many digits of n, are divisible by m.
"""
ans = 0 # initiate counter
while n:
# generate quotient and remainder when divided by 10
n, r = divmod(n, 10)
# increase counter by 1, if remainder is divisible by m
ans += (r % m) == 0
return ans
>>> solution(n=650899, m=3)
4
好的,如果您要计算较大数字中的数字,即 integer 是另一个数字的倍数,则可以通过模数和除法来完成:
def digitsThatAreMults(checkNum, digit):
# Init count to zero, we'll increment for every digit that matches.
count = 0
# Continue until no digits left.
while checkNum != 0:
# Digit is a multiple if no remainder when dividing.
if (checkNum % 10) % digit == 0:
count += 1
# Debugging line to see in action.
print("dbg", count, checkNum)
# Strip off digit you just tested.
checkNum = checkNum // 10
# Now just return the count of the matches.
return count
# Test harness, you may want to add some more test cases for decent coverage :-)
print(digitsThatAreMults(650899, 3))
使用那里的调试行,您可以看到它是如何工作的,检查每个数字(最后一个)并增加计数(如果它是倍数):
dbg 1 650899
dbg 2 65089
dbg 2 6508
dbg 3 650
dbg 3 65
dbg 4 6
4
一旦你对代码感到满意,你就可以删除调试行,虽然我倾向于把东西留在里面,只是把它们注释掉,因为你经常不得不回来调试一些你没想到的奇怪边缘情况的代码的:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.