Leetcode 1281. Subtract the Product and Sum of Digits of an Integer
Leetcode Problem 1281: “Subtract the Product and Sum of Digits of an Integer”
Given an integer number n
, the task is to:
Example:
Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
Q: What is the range of the input integer n
?
A: We assume n
is a positive integer as the problem domain usually deals with positive integers unless otherwise specified.
Q: Can the input integer n
be a single digit?
A: Yes, though in such cases the product and sum would be the same, resulting in a difference of 0.
#include <iostream>
class Solution {
public:
int subtractProductAndSum(int n) {
int product = 1;
int sum = 0;
while (n > 0) {
int digit = n % 10;
product *= digit;
sum += digit;
n /= 10;
}
return product - sum;
}
};
int main() {
Solution solution;
int n = 234; // example input
std::cout << "Result: " << solution.subtractProductAndSum(n) << std::endl;
return 0;
}
product
to 1 (as multiplying by 1 has no effect).sum
to 0 (as adding 0 has no effect).n
.n % 10
).sum
.product
.n /= 10
).sum
from product
and return the result.n
. Each digit is processed exactly once.product
and sum
).This solution efficiently processes each digit of the number and computes the desired result in a linear time relative to the number of digits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?