Problem 2520

Abstract / Summary

Given a number, count how many of its digits divide the number evenly.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2520.py

class Solution:
    def countDigits(self, num: int) -> int:
        return sum(1 for c in str(num) if num % int(c) == 0)
3 lines | 124 bytes | submitted December 21, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 86% (200k+ submissions).

Typical patterns to solve this problem:
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a single method countDigits that receives an integer num and returns the count of its digits that evenly divide the original number. The solution follows a concise functional style, leveraging Python’s built-in sum together with a generator expression to perform the calculation in a single line.

Key Steps

The core logic can be broken down into three conceptual operations, each illustrated with a focused snippet.

Conversion of the integer to an iterable sequence of characters

str_num = str(num)

By turning the integer into its string representation, each digit becomes an individual character that can be traversed without additional arithmetic.

Evaluation of the divisibility condition for each digit

for c in str_num:
    digit = int(c)
    if num % digit == 0:
        # digit contributes to the count

Inside the generator expression, each character c is cast back to an integer digit. The modulo operation num % digit determines whether the digit is a divisor of the original number. Only digits satisfying this condition are considered.

Aggregation of the qualifying digits

result = sum(1 for c in str_num if num % int(c) == 0)

The generator yields the constant value 1 for every digit that passes the divisibility test. The surrounding sum aggregates these ones, producing the final count.

Edge Cases

The algorithm inherently handles numbers of varying length, including single-digit inputs. When the input consists solely of digits that do not divide the number, the generator yields no values and sum returns zero, correctly indicating that no digit satisfies the condition.

Digits equal to zero present a special situation because division by zero is undefined. In such cases, the modulo expression cannot be evaluated, and the digit is effectively excluded from the count. Consequently, numbers containing zero digits do not contribute those digits to the final tally.

Negative numbers are transformed to their string form including the leading minus sign. The minus sign is not a numeric character, so it is ignored by the generator’s int(c) conversion, which would raise an exception if encountered. Therefore, the method is intended for non-negative inputs, and the conversion step naturally filters out non-digit characters.

Performance Optimizations

The implementation avoids constructing intermediate collections by using a generator expression directly within sum. This lazy evaluation means that each digit is processed and discarded immediately after its contribution is accounted for, minimizing memory overhead.

Converting the entire number to a string once, rather than repeatedly extracting digits via arithmetic operations, reduces the number of costly integer divisions. The per-digit int(c) conversion is lightweight compared to repeated modulo calculations on the original integer.

By returning the result of the single sum call, the function eliminates the need for explicit loops or accumulator variables, allowing the Python interpreter to execute the operation with minimal bytecode overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a magical machine that is given a secret number like one hundred and twenty-four. First, the machine peels apart the number to look at each digit, which are the one, the two, and the four. Then, the machine takes the original big number and tries to divide it by each of those little digits one by one. If a digit fits perfectly into the big number without leaving any extra crumbs behind, the machine keeps that digit to count it later. After checking every single digit, the machine finishes its job by telling the count of how many digits were able to divide the big number perfectly.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.42 | σ = 1.88

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python Java C++ TS
WalkCCC Python Java C++
leetcode.ca Python Java C++ C Go Rust TS
Progiez Python Java C++
github chandansgowda Python
charles-wangkai Java
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
chandansgowda Python
charles-wangkai Java
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
varunu28 Java
24 links | 11 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

10 solutions   December 21, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality