Count the Digits That Divide a Number — Problem & Solution
Count the Digits That Divide a Number solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Count the Digits That Divide a Number is an easy coding problem on math, asked in Amazon, TCS and Capgemini interviews.
- Difficulty: Easy
- Topics: Math
- Asked at: Amazon, TCS, Capgemini
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given an integer num, return the number of its digits that divide num exactly.
A digit d divides num if num % d == 0. Digits equal to 0 never divide anything and are simply skipped.
Example 1
Input: num = 7
Output: 1
Explanation: 7 divides 7.
Example 2
Input: num = 121
Output: 2
Explanation: Both 1s divide 121; the 2 does not.
Example 3
Input: num = 1248
Output: 4
Explanation: 1, 2, 4 and 8 all divide 1248.
Constraints
1 <= num <= 1000000000num does not contain the digit 0 in the given tests unless noted.
Hints for Count the Digits That Divide a Number
Hint 1
Peel digits off with
% 10and/ 10— do not build a string unless you want to.Hint 2
Keep the original value around; you divide by each digit, not by the shrinking remainder.
Hint 3
Skip a zero digit rather than dividing by it.
How to solve Count the Digits That Divide a Number
Extract each digit and test it against the original number. The only trap is remembering to compare against num, not the value being shifted.
Approach
- Copy
numinto a working variablex. - While
x > 0, taked = x % 10. - Count
dwhen it is non-zero andnum % d == 0. - Divide
xby 10 and continue.
Why it works
Each digit is visited exactly once, and the divisibility test uses the unchanged original — which is what the definition asks.
Complexity
- Time —
O(log num) - Space —
O(1)
Pitfalls
- Testing
x % dinstead ofnum % dcompares against the truncated remainder. - Dividing by a zero digit crashes or yields NaN — skip it.
- Repeated digits each count separately, as
121shows.
Reference solution
Python
def countDigits(num: int) -> int:
count = 0
x = num
while x > 0:
d = x % 10
if d != 0 and num % d == 0:
count += 1
x //= 10
return countJava
public static int countDigits(int num) {
int count = 0, x = num;
while (x > 0) {
int d = x % 10;
if (d != 0 && num % d == 0) count++;
x /= 10;
}
return count;
}C++
int countDigits(int num) {
int count = 0, x = num;
while (x > 0) {
int d = x % 10;
if (d != 0 && num % d == 0) count++;
x /= 10;
}
return count;
}JavaScript
var countDigits = function(num) {
let count = 0, x = num;
while (x > 0) {
const d = x % 10;
if (d !== 0 && num % d === 0) count++;
x = Math.floor(x / 10);
}
return count;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.