Check Divisibility by Digit Sum and Product (LeetCode 3622): Solution and Explanation
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
- Set
s = 0,p = 1, and copyx = n. - While
x > 0, taked = x % 10. - Add
dtosand multiplypbyd. - Drop the digit with
x //= 10. - Return
n % (s + p) == 0.
Step-by-step example
n = 99
- s = 0, p = 1, x = 99.
- d = 9: s = 9, p = 9, x = 9.
- d = 9: s = 18, p = 81, x = 0.
- 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) == 01class Solution {
2 public boolean checkDivisibility(int n) {
3 int s = 0, p = 1;
4 int x = n;
5 while (x > 0) {
6 int d = x % 10;
7 s += d;
8 p *= d;
9 x /= 10;
10 }
11 return n % (s + p) == 0;
12 }
13}1class Solution {
2public:
3 bool checkDivisibility(int n) {
4 int s = 0, p = 1;
5 int x = n;
6 while (x > 0) {
7 int d = x % 10;
8 s += d;
9 p *= d;
10 x /= 10;
11 }
12 return n % (s + p) == 0;
13 }
14};Time and space complexity
O(log n)
One loop iteration per digit, and n has at most 7 digits.
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
nitself 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.