简体   繁体   中英

Trying to figure out how many digits in a number are a multiple of another digit

I'm trying to write a function that takes in two elements n and m and will try to give a count of the digits in n that are multiples of m .

For example, if n = 650899, m = 3 , the answer is 4 because the digits {6, 0, 9, 9} are all evenly divisible by 3 , while the digits {5, 8} are not:

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

I'm trying to do this without using strings at all (such as by checking individual characters within the string). Does anyone know how I can manipulate just the number by itself?

Try the following:

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

Okay, if you're after a count of the digits in your larger number that are an integer multiple of another digit, that can be done with modulo and division:

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))

With the debug line in there, you can see how it works, checking each digit (the one at the end) and increasing the count if it's a multiple:

dbg 1 650899
dbg 2 65089
dbg 2 6508
dbg 3 650
dbg 3 65
dbg 4 6
4

Once you're happy with code, you can delete the debug line, though I tend to leave things in there and just comment them out, since you often have to come back and debug the code for some bizarre edge case you didn't think of:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM