Count Digits
Problem Statement : Count Digits
Problem Statement
Given a positive integer n, count how many of its digits evenly divide n.
A digit
dofnevenly dividesnif:
d ≠ 0(to avoid division by zero), and
n % d == 0.
Examples
Example 1:
-
Input:
n = 12 -
Digits: 1, 2
-
Check:
-
12 % 1 == 0 → ✅
-
12 % 2 == 0 → ✅
-
-
Output:
2
Example 2:
-
Input:
n = 2446 -
Digits: 2, 4, 4, 6
-
Check:
-
2446 % 2 == 0 → ✅
-
2446 % 4 == 2 → ❌
-
2446 % 6 == 2 → ❌
-
-
Output:
1
Example 3:
-
Input:
n = 23 -
Digits: 2, 3
-
Check:
-
23 % 2 != 0
-
23 % 3 != 0
-
-
Output:
0
Constraints
1 ≤ n ≤ 10^5
Intuition
To solve this, we need to:
-
Traverse each digit of the number.
-
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
-
Store the original number in a separate variable, say
cpy. -
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.
-
-
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
-
cpy = 124,cnt = 0 -
Loop 1:
-
r = 4 -
124 % 4 = 0→ ✅ →cnt = 1 -
n = 12
-
-
Loop 2:
-
r = 2 -
124 % 2 = 0→ ✅ →cnt = 2 -
n = 1
-
-
Loop 3:
-
r = 1 -
124 % 1 = 0→ ✅ →cnt = 3 -
n = 0
-
-
Output:
3
Time Complexity
- O(log₁₀(n))
The number of digits inndetermines the number of iterations.
Space Complexity
- O(1)
Constant space is used for variables.
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.