LC 1281.Subtract the Product and Sum of Digits of an Integer

题目描述

这是 LeetCode 上的 1281. 整数的各位积和之差 ,难度为简单

给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。

示例 1:

1
2
3
4
5
6
输入:n = 234
输出:15
解释:
各位数之积 = 2 * 3 * 4 = 24
各位数之和 = 2 + 3 + 4 = 9
结果 = 24 - 9 = 15

示例 2:

1
2
3
4
5
6
输入:n = 4421
输出:21
解释:
各位数之积 = 4 * 4 * 2 * 1 = 32
各位数之和 = 4 + 4 + 2 + 1 = 11
结果 = 32 - 11 = 21

提示:

  • 1 <= n <= 10^5

解答

方法一:模拟

根据题意每次对 n 取余求出每个位数并相应地加到总和,乘到乘积中即可,最后返回差值。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int subtractProductAndSum(int n) {
int sum = 0, mul = 1;
while (n != 0) {
int tmp = n % 10;
sum += tmp;
mul *= tmp;
n /= 10;
}
return mul - sum;
}
}
  • 时间复杂度\(O(\log n)\),其中 n 为整数 n 的大小。

  • 空间复杂度\(O(1)\)

每题一图


LC 1281.Subtract the Product and Sum of Digits of an Integer
https://chen-huaneng.github.io/2023/12/11/2023-12-11-2023-12-11-lc-1281/
作者
Abel
发布于
2023年12月11日
更新于
2023年12月11日
许可协议