题目
给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。
示例 1:
输入:n = 234
输出:15
解释:
各位数之积 = 2 * 3 * 4 = 24
各位数之和 = 2 + 3 + 4 = 9
结果 = 24 - 9 = 15
示例 2:
输入:n = 4421
输出:21
解释:
各位数之积 = 4 * 4 * 2 * 1 = 32
各位数之和 = 4 + 4 + 2 + 1 = 11
结果 = 32 - 11 = 21
思路
本题重点在于将整数的每位数取出,利用循环取余,除10的方法来实现。代码如下:
class Solution {
public:
int subtractProductAndSum(int n) {
int chengji=1;
int qiuhe=0;
int result;
while(n){
chengji *=(n%10);
qiuhe +=(n%10);
n /= 10;
}
result = chengji - qiuhe;
return result;
}
};
结果: