试图找出一个数中有多少位是另一个数的倍数

  • 本文关键字:多少 另一个 一个 python
  • 更新时间 :
  • 英文 :


我正试图编写一个函数,该函数接受两个元素nm,并将尝试给出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

好了,如果你想要的是一个大数的整数倍,那就可以用取模和除法来完成

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

一旦你对代码感到满意,你可以删除调试行,虽然我倾向于把东西留在那里,只是把它们注释掉,因为你经常不得不回来调试代码,因为一些奇怪的边缘情况你没有想到:-)

相关内容

最新更新