#3622
Check Divisibility by Digit Sum and Product
EasyMathMathematical OperationsDigit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(d) | O(d) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(d)Space O(1)
Directly compute the digit sum and product in a single pass through the digits, minimizing operations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize sum and product variables.
- 2Step 2: Loop through each digit, updating sum and product.
- 3Step 3: Check if n is divisible by the sum of sum and product.
solution.py9 lines
1def check_divisibility(n):
2 digit_sum, digit_product = 0, 1
3 temp = n
4 while temp > 0:
5 digit = temp % 10
6 digit_sum += digit
7 digit_product *= digit
8 temp //= 10
9 return n % (digit_sum + digit_product) == 0ℹ
Complexity note: The time complexity is O(d) where d is the number of digits in n, achieved by processing each digit once.
- 1Divisibility checks often involve sums or products of components.
- 2Single-pass calculations can optimize performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.