Count the Digits That Divide a Number

This problem requires us to count the number of digits in a number that divide the number itself. To solve this, we first convert the number to a string, then iterate over each digit. We check if the number is divisible by each digit, and if it is, we increment a counter.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def countDigits(self, num: int) -> int:
        num_str = str(num)
        count = 0

        for digit_str in num_str:
            digit = int(digit_str)

            if num % digit == 0:
                count += 1

        return count

In this code:

  • We first convert num to a string, num_str.
  • We initialize a counter count to 0.
  • We then iterate over each character digit_str in num_str, converting it back to an integer digit.
  • If num is divisible by digit (i.e., num % digit == 0), we increment count.
  • Finally, we return count, which represents the number of digits in num that divide num.

This code works under the assumption that num does not contain the digit 0, as stated by the problem constraints, so we don’t have to check for division by zero.