[英]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.