超简单,给Python和C++两种解法:
1、Python※ 2、C++※
方法:直接遍历取模
1、C++
class Solution {
public:
int subtractProductAndSum(int n) {
int p = 0, t = 1;
while (n > 0) {
int digit = n % 10;
n /= 10;
p += digit;
t *= digit;
}
return t - p;
}
};
2、Python
class Solution:
def subtractProductAndSum(self, n: int) -> int:
add, mul = 0, 1
while n > 0:
digit = n % 10
n //= 10
add += digit
mul *= digit
return mul - add