Count the Digits That Divide a Number (LeetCode 2520): Solution and Explanation

Easy
Math

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

  1. Set count = 0 and copy x = num.
  2. While x > 0, take the last digit d = x % 10.
  3. If num % d == 0, add one to count.
  4. Drop the digit with x //= 10 and repeat.
  5. Return count.

Step-by-step example

num = 7
  1. count = 0, x = 7.
  2. d = 7 % 10 = 7.
  3. 7 % 7 = 0, so 7 divides 7 and count becomes 1.
  4. 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 count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(log num)

The loop runs once per digit, and num has about log10(num) digits, at most 10 here.

Space

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 x instead of the original num.
  • Counting each distinct digit once. A digit that appears twice and divides num counts twice.
  • Using / in JavaScript without Math.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.