Count the Digits That Divide a Number (LeetCode 2520): Solution and Explanation
Given an integer num with no zero digits, return how many of its digits divide num evenly, counting a repeated digit once per appearance.
Intuition
The work splits into two small jobs: get each digit on its own, and check whether it divides the number.
x % 10 is always the last digit of x, and x // 10 removes that digit. Repeating the pair walks through every digit from right to left without converting to a string.
The test must use the original num, so keep it untouched and peel digits from a copy x. Since the constraints rule out the digit 0, num % d never divides by zero.
Approach: Peel digits with % 10
- Set
count = 0and copyx = num. - While
x > 0, take the last digitd = x % 10. - If
num % d == 0, add one tocount. - Drop the digit with
x //= 10and repeat. - Return
count.
Step-by-step example
num = 7
- count = 0, x = 7.
- d = 7 % 10 = 7.
- 7 % 7 = 0, so 7 divides 7 and count becomes 1.
- x = 7 // 10 = 0, the loop ends and we return 1.
Code: Python, Java, C++
1class Solution:
2 def countDigits(self, num: int) -> int:
3 count = 0
4 x = num
5 while x > 0:
6 d = x % 10
7 if num % d == 0:
8 count += 1
9 x //= 10
10 return count1class Solution {
2 public int countDigits(int num) {
3 int count = 0;
4 int x = num;
5 while (x > 0) {
6 int d = x % 10;
7 if (num % d == 0) {
8 count++;
9 }
10 x /= 10;
11 }
12 return count;
13 }
14}1class Solution {
2public:
3 int countDigits(int num) {
4 int count = 0;
5 int x = num;
6 while (x > 0) {
7 int d = x % 10;
8 if (num % d == 0) {
9 count++;
10 }
11 x /= 10;
12 }
13 return count;
14 }
15};Time and space complexity
O(log num)
The loop runs once per digit, and num has about log10(num) digits, at most 10 here.
O(1)
Only a few integer variables are kept.
Other approaches
String conversion (time O(log num), space O(log num))
Turn num into a string and loop over its characters, converting each back to an integer. It reads naturally but allocates a string.
Cache per distinct digit (time O(log num), space O(1))
Precompute whether each digit 1 to 9 divides num and then count digits with a lookup. It saves nothing at this size but shows the idea for repeated queries.
Common mistakes
- Testing the digit against the shrinking copy
xinstead of the originalnum. - Counting each distinct digit once. A digit that appears twice and divides num counts twice.
- Using
/in JavaScript withoutMath.floor, which leaves a fraction and makes the loop run forever on tiny values.
Frequently asked questions
Why can't num % d divide by zero?
The problem guarantees num has no 0 digit, so every d is between 1 and 9.
Does the digit 1 always count?
Yes. Every integer is divisible by 1, so each 1 in num adds one to the answer.
Is the string approach acceptable in an interview?
Yes. The arithmetic version is a touch more memory friendly and shows you know the % 10 and // 10 pattern, which comes up in many digit problems.