3622. Check Divisibility by Digit Sum and Product
EasyView on LeetCode
Problem Overview
You only need two numbers from the digits of n: their sum and their product.
Intuition
You only need two numbers from the digits of n: their sum and their product. Add those together and ask whether n is a multiple of that total. Walking digits with modulo 10 is enough - no extra data structure.
Algorithm
- 1Copy n. Start sum = 0 and product = 1.
- 2While the copy is non-zero: take the last digit (copy % 10), add it to the sum, multiply it into the product, then drop it (copy / 10).
- 3Let total = sum + product.
- 4Return whether n % total == 0.
Example Walkthrough
Input: n = 99
- 1.Digits 9 and 9: sum = 18, product = 81, total = 99.
- 2.99 % 99 == 0, so the answer is true.
Output: true
Common Pitfalls
- •A zero digit zeros the product. The divisor then equals the digit sum, which is still valid.
- •Start the product at 1, not 0, or every answer becomes n % sum.
- •Do not mutate n while peeling digits if you still need the original for the modulo check.
- •Constraints keep n small, so digit product will not overflow a 32-bit int.
3622.cs
C#
// Approach: Peel digits with n % 10. Accumulate sum and product, then test
// whether n is divisible by (sum + product). A zero digit makes the product
// 0, which is fine: the divisor becomes the digit sum alone.
// Complexity: O(log n) time and O(1) space.
public class Solution
{
public bool CheckDivisibility(int n)
{
int digitSum = 0;
int digitProduct = 1;
int number = n;
while (number != 0)
{
int currentDigit = number % 10;
number /= 10;
digitSum += currentDigit;
digitProduct *= currentDigit;
}
int total = digitSum + digitProduct;
return n % total == 0;
}
}
Was this solution helpful?
Related Problems
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 29. Divide Two Integers(Medium)
- 66. Plus One(Easy)
- 67. Add Binary(Easy)
- 70. Climbing Stairs(Easy)