Count Digits

Problem Statement : Count Digits


Problem Statement

Given a positive integer n, count how many of its digits evenly divide n.

A digit d of n evenly divides n if:


Examples

Example 1:

Example 2:

Example 3:


Constraints


Intuition

To solve this, we need to:

  1. Traverse each digit of the number.

  2. Check whether it is non-zero and whether it evenly divides the original number.

We use modulus and division operations to extract each digit and perform the required checks.


Approach

  1. Store the original number in a separate variable, say cpy.

  2. Loop through each digit of n:

    • Extract the last digit using n % 10.

    • Ignore the digit if it is 0.

    • If cpy % digit == 0, increment the count.

    • Remove the last digit by doing n /= 10.

  3. Return the final count.


Java Code

class Solution {
    static int evenlyDivides(int n) {
        int cpy = n;      // Store original number
        int cnt = 0;      // Count of digits that divide n
        while (n > 0) {
            int r = n % 10;        // Extract last digit
            if (r != 0 && cpy % r == 0) {
                cnt++;             // Check and increment count
            }
            n /= 10;               // Remove last digit
        }
        return cnt;
    }
}

Dry Run

Input: n = 124


Time Complexity


Space Complexity


Conclusion

This approach efficiently checks each digit for divisibility and handles edge cases like division by zero. It is optimal for the given constraints and showcases clean use of arithmetic operations for digit-level processing.