Members of the product and the difference between integer arithmetic of endless

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%10to achieve traverse effect.
For 字符串, the general should be good to run charto 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;
    }
}
Published 125 original articles · won praise 236 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_33709508/article/details/103816546