LeetCodeAnimation/1281- subtract-the-product-and-sum-of-digits-of-an-integer/Article/1281- subtract-the-product-and-sum-of-digits-of-an-integer.md
程序员吴师兄 29df7e5b9a 0461、0477、1281 solved
0461、0477、1281 solved
2020-05-06 10:39:21 +08:00

68 lines
1.1 KiB
Java
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

### 题目描述
给你一个整数 `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
```
**提示**
```
1 <= n <= 10^5
```
### 题目解析
1通过取模运算遍历数字每一位
2通过两个变量在遍历过程中分别记录求和与求积
### 动画理解
![](../Animation/Animation.mp4)
### 参考代码
```java
class Solution {
public int subtractProductAndSum(int n) {
int addResult = 0, mulResult = 1;
while (n > 0) {
int num = n % 10;
n /= 10;
addResult += num;
mulResult *= num;
}
return mulResult - addResult;
}
}
```
### 复杂度分析
时间复杂度O(logN)
空间复杂度O(1)