We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count the Digits That Divide a Number

Number: 2608

Difficulty: Easy

Paid? No

Companies: Google, tcs


Problem Description

Given an integer num, count the number of digits in num that evenly divide num (i.e., for a digit d, num % d == 0). Each occurrence of a digit that divides num is counted, and the number does not contain any zero digits.


Key Insights

  • Convert the number to a string to iterate over each digit.
  • For each digit, convert it back to an integer and check if it divides the number evenly using the modulo operation.
  • Since the number does not contain zero, directly perform the division check.
  • Each valid digit, even if repeated, is counted separately.

Space and Time Complexity

Time Complexity: O(d), where d is the number of digits in num (log10(num)).
Space Complexity: O(d) for storing the string representation, which is negligible.


Solution

The solution involves converting the integer to its string representation to easily iterate over each digit. For each digit, convert it back into an integer and check if it divides the original integer without leaving a remainder using the modulo operator. A counter is incremented each time a digit divides the number evenly. This simple linear approach handles all cases and respects the constraints of the problem.


Code Solutions

# Define a function to count the divisibility digits
def count_dividing_digits(num):
    # Convert the number to a string to iterate over each digit
    num_str = str(num)
    # Initialize a counter for valid digits
    valid_count = 0
    # Iterate over each character in the string representation
    for char in num_str:
        # Convert the character back to an integer digit
        digit = int(char)
        # Check if the digit divides num evenly
        if num % digit == 0:
            valid_count += 1  # Increment the count when condition is met
    return valid_count

# Example call to the function
print(count_dividing_digits(1248))  # Expected output: 4
← Back to All Questions