#2520

Count the Digits That Divide a Number

Easy
MathMathematical operationsDigit extraction
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution still checks each digit but avoids unnecessary conversions and uses a more efficient loop. This approach is similar to the brute force but is streamlined for performance.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a counter to zero.
  2. 2Step 2: Use a while loop to extract digits from the number until it becomes zero.
  3. 3Step 3: For each extracted digit, check if it divides the original number.
  4. 4Step 4: If it does, increment the counter.
  5. 5Step 5: Return the counter as the result.
solution.py9 lines
1def countDigits(num):
2    count = 0
3    original = num
4    while num > 0:
5        digit = num % 10
6        if digit != 0 and original % digit == 0:
7            count += 1
8        num //= 10
9    return count

Complexity note: The time complexity remains O(n) as we still process each digit, but we do it more efficiently without converting to strings. The space complexity is O(1) since we only use a fixed amount of extra space.

  • 1Digits should be checked individually for divisibility.
  • 2Avoid division by zero by ensuring digits are non-zero.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.