Check Divisibility by Digit Sum and Product (LeetCode 3622): Solution and Explanation

Easy
Math

Given a positive integer n, return whether n is divisible by the sum of its digit sum and its digit product.

Intuition

Both quantities come from the same digits, so one loop over the digits can build them side by side.

Addition starts from 0 and multiplication starts from 1, because those values leave the first digit unchanged.

The divisor can never be 0: the leading digit of n is at least 1, so the digit sum alone is at least 1. A zero digit only sets the product to 0.

Approach: One pass over the digits

  1. Set s = 0, p = 1, and copy x = n.
  2. While x > 0, take d = x % 10.
  3. Add d to s and multiply p by d.
  4. Drop the digit with x //= 10.
  5. Return n % (s + p) == 0.

Step-by-step example

n = 99
  1. s = 0, p = 1, x = 99.
  2. d = 9: s = 9, p = 9, x = 9.
  3. d = 9: s = 18, p = 81, x = 0.
  4. s + p = 99 and 99 % 99 = 0, so return true.

Code: Python, Java, C++

1class Solution:
2    def checkDivisibility(self, n: int) -> bool:
3        s, p = 0, 1
4        x = n
5        while x > 0:
6            d = x % 10
7            s += d
8            p *= d
9            x //= 10
10        return n % (s + p) == 0
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(log n)

One loop iteration per digit, and n has at most 7 digits.

Space

O(1)

Only s, p and the working copy x are stored.

Other approaches

String digits (time O(log n), space O(log n))

Convert n to a string, then sum and multiply the characters as integers. Same idea with a small extra allocation.

Two separate loops (time O(log n), space O(1))

Compute the digit sum in one loop and the product in another. Correct, but it reads the digits twice for no benefit.

Common mistakes

  • Starting the product at 0, which keeps it 0 forever.
  • Peeling digits from n itself and then testing the destroyed value instead of the original.
  • Worrying about division by zero. It cannot happen, because the digit sum of a positive integer is at least 1.

Frequently asked questions

Can the product overflow a 32-bit integer?

No. n has at most 7 digits, so the product is at most 9^6 = 531441 for values up to 10^6.

What happens when n contains a 0?

The product becomes 0, so the test reduces to whether n is divisible by its digit sum. For n = 120 that is 3, and 120 % 3 = 0.

Is n = 1 divisible?

No. Its digit sum and product are both 1, so the divisor is 2, and 1 % 2 = 1.