Leetcode 1281. Subtract the Product and Sum of Digits of an Integer
You are given an integer n
. Return the difference between the product of its digits and the sum of its digits.
n
?
n
is a positive integer, typically constrained by the input limits of the platform.n
has only one digit?
n
has only one digit, the product and the sum of that digit will be the same, and their difference will be zero.product
to 1
and sum
to 0
.n
is greater than 0
:
n % 10
.product
by multiplying it by the extracted digit.sum
by adding the extracted digit.n
using integer division n = n / 10
.product
and sum
.public 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;
}
}
The time complexity of the solution is O(d), where d
is the number of digits in the integer n
. This is because each digit is processed exactly once.
Let’s walk through an example for better understanding:
n = 234
The function returns 15
as expected.
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?