Problem
3622. Check Divisibility by Digit Sum and Product
Logic
- Extract digits of
nusing% 10and/ 10while iterating through a copy ofn. - Track the sum of digits in
digitSum(initialized to0) and the product of digits indigitProduct(initialized to1). - Calculate the combined
divisor = digitSum + digitProduct. - Guard against division by zero (
divisor == 0). - Return whether
nis divisible bydivisor(n % divisor == 0).
Code
class Solution {
public:
bool checkDivisibility(int n) {
int nc = n;
int digitSum = 0;
int digitProduct = 1;
while (nc != 0) {
int digit = nc % 10;
nc /= 10;
digitSum += digit;
digitProduct *= digit;
}
int divisor = digitSum + digitProduct;
if (divisor == 0) {
return false;
}
return (!(n % divisor));
}
};