Source: LeetCode
Link: https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
1281. The difference between the sum of the individual bits of an integer
Give you an integer n, please help calculate and return the difference between the "product of each number" and the "sum of each number".
Example 1:
Input: n = 234
Output: 15
Explanation:
The product of the digits = 2 * 3 * 4 = 24 The
sum of the digits = 2 + 3 + 4 = 9
Result = 24-9 = 15
Example 2:
Input: n = 4421
Output: 21
Explanation:
Product of digits = 4 * 4 * 2 * 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32-11 = 21
prompt:
1 <= n <= 10^5
Implementation code
public class Solution {
public int subtractProductAndSum(int n) {
int sum=0,product = 1,temp;
while(n>0){
temp = n%10;
n = n/10;
sum += temp;
product *= temp;
}
return product - sum;
}
}