LC.P1281[整数的各位积和之差]

方法一:模拟

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int subtractProductAndSum(int n) {
int prod = 1, sum = 0;
while (n > 0) {
int x = n % 10;
n /= 10;
prod *= x;
sum += x;
}
return prod - sum;
}
}
  • 时间复杂度:$O(logn)$
  • 空间复杂度:$O(1)$