我正在尝试编写一个接受两个元素的函数 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
关于python - 试图找出一个数字中有多少位是另一个数字的倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65804535/