参考链接
- https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
题目描述
给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。
解题思路
每次对10取余,取出最后一位数,更新总的和与积,再将数除10,如此循环直到只有一位数。
代码
class Solution {
public:
int subtractProductAndSum(int n) {
int mul = 1;
int sum = 0;
while(n / 10 != 0)
{
sum += n % 10;
mul *= n % 10;
n = n / 10;
}
sum += n;
mul *= n;
return mul - sum;
}
};