To give you an integer n, please help calculate and return the integer difference "product you figures" and "figures and" the.
Example 1:
Input: n = 234
Output: 15
Explanation:
Each digit of the product = 2 * 3 * 4 = 24
each digit sum = 2 + 3 + 4 = 9
Results = 24--9 = 15
Example 2:
Input: n = 4421
Output: 21
Explanation:
Each digit of the product = 4 * 4 * 2 * 1 = 32
Each digit sum = 4 + 2 + 4 + 11 = 1
Results = 32--11 = 21
prompt:
1 <= n <= 10^5
Key study
For 数字
, the general should be adept n%10
to achieve traverse effect.
For 字符串
, the general should be good to run char
to achieve the effect of traversal
answer
class Solution {
public int subtractProductAndSum(int n) {
int sum=0;
int product=1;
while (n>0){
int digit=n%10;
sum+=digit;
product*=digit;
n=n/10;
}
return product-sum;
}
}