题目描述
给你一个整数 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
提示:
解法
方法一:模拟
我们用两个变量 $x$ 和 $y$ 分别记录各位数之积、各位数之和,初始时 $x=1,y=0$。
当 $n \gt 0$ 时,每次将 $n$ 对 $10$ 取模得到当前位的数字 $v$,并将 $n$ 除以 $10$ 后继续进行下一次循环。在每次循环中,我们更新 $x = x \times v$, $y = y + v$。
最终,我们返回 $x - y$ 即可。
时间复杂度 $O(\log n)$,其中 $n$ 是题目给定的整数。空间复杂度 $O(1)$。
| class Solution:
def subtractProductAndSum(self, n: int) -> int:
x, y = 1, 0
while n:
n, v = divmod(n, 10)
x *= v
y += v
return x - y
|
| class Solution {
public int subtractProductAndSum(int n) {
int x = 1, y = 0;
for (; n > 0; n /= 10) {
int v = n % 10;
x *= v;
y += v;
}
return x - y;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12 | class Solution {
public:
int subtractProductAndSum(int n) {
int x = 1, y = 0;
for (; n; n /= 10) {
int v = n % 10;
x *= v;
y += v;
}
return x - y;
}
};
|
| func subtractProductAndSum(n int) int {
x, y := 1, 0
for ; n > 0; n /= 10 {
v := n % 10
x *= v
y += v
}
return x - y
}
|
| function subtractProductAndSum(n: number): number {
let [x, y] = [1, 0];
for (; n > 0; n = Math.floor(n / 10)) {
const v = n % 10;
x *= v;
y += v;
}
return x - y;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13 | impl Solution {
pub fn subtract_product_and_sum(mut n: i32) -> i32 {
let mut x = 1;
let mut y = 0;
while n != 0 {
let v = n % 10;
n /= 10;
x *= v;
y += v;
}
x - y
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12 | public class Solution {
public int SubtractProductAndSum(int n) {
int x = 1;
int y = 0;
for (; n > 0; n /= 10) {
int v = n % 10;
x *= v;
y += v;
}
return x - y;
}
}
|
| int subtractProductAndSum(int n) {
int x = 1;
int y = 0;
for (; n > 0; n /= 10) {
int v = n % 10;
x *= v;
y += v;
}
return x - y;
}
|
方法二