#2520
Count the Digits That Divide a Number
Easy Digit extraction + modulo
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Count how many digits of num (counting repeats) divide num evenly. num contains no zero digits.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: for each digit of the number, does it divide the whole number evenly?
Why this works: walk the digits on a copy, but test divisibility on the original number.
Example: num = 1248
8: 1248 % 8 = 0 ✓4: 1248 % 4 = 0 ✓2: 1248 % 2 = 0 ✓1: 1248 % 1 = 0 ✓ → 4
✦Hints open one at a time
Keep the original number in a separate variable — you'll destroy the copy while extracting digits.
A digit d divides num when num % d == 0.
↗Approach
Copy num, extract each digit from the copy, and test the original with modulo.
</>Solution (Java)
class Solution {
public int countDigits(int num) {
int count = 0;
for (int x = num; x > 0; x /= 10) {
if (num % (x % 10) == 0) count++; // digit divides the ORIGINAL number
}
return count;
}
}
!Common mistake
Testing divisibility against the shrinking copy instead of the original number.
Complexity
- Time: O(log10 n).
- Space: O(1).
