algoadvance

Given an integer num, return the number of digits in num that divide num.

A digit divides num if num % digit == 0.

Example:

Input: num = 121
Output: 2
Explanation: 121 is divisible by its digit 1, but not by its digit 2. Thus, 2 digits divide 121.

Constraints:

Clarifying Questions:

  1. Q: Should we consider the digit 0 in the number?
    • A: No, because division by zero is not defined and it’s not possible to divide by zero.
  2. Q: What if the number is negative?
    • A: The number is always positive as per constraints ( 1 \leq num \leq 10^9 ).
  3. Q: Should the result include multiple occurrences of the same digit?
    • A: Yes, every occurrence of a digit that divides the number should be counted.

Strategy:

  1. Convert the number to a string to easily traverse through each digit.
  2. Iterate through each digit in the string representation.
  3. Check if the digit is not zero and if the digit divides the number.
  4. Count the digits which divide the number.
  5. Return the count.

Time Complexity:

Code:

def count_digits(num: int) -> int:
    count = 0
    for digit in str(num):
        if digit != '0' and num % int(digit) == 0:
            count += 1
    return count

# Test cases
print(count_digits(121))  # Output: 2
print(count_digits(12345))  # Output: 2 (1 and 5 divide 12345)
print(count_digits(100))  # Output: 1 (only 1 divides 100)

Explanation:

This approach ensures we account for all digits and their divisibility while handling the potential issue of division by zero.

Try our interview co-pilot at AlgoAdvance.com