LeetCode 题解工作台
整数的各位积和之差
给你一个整数 n ,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。 示例 1: 输入: n = 234 输出: 15 解释: 各位数之积 = 2 * 3 * 4 = 24 各位数之和 = 2 + 3 + 4 = 9 结果 = 24 - 9 = 15 示例 2: 输入: n = 44…
1
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
我们用两个变量 和 分别记录各位数之积、各位数之和,初始时 。 当 $n \gt 0$ 时,每次将 对 取模得到当前位的数字 ,并将 除以 后继续进行下一次循环。在每次循环中,我们更新 $x = x \times v$, $y = y + v$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
给你一个整数 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
解题思路
方法一:模拟
我们用两个变量 和 分别记录各位数之积、各位数之和,初始时 。
当 时,每次将 对 取模得到当前位的数字 ,并将 除以 后继续进行下一次循环。在每次循环中,我们更新 , 。
最终,我们返回 即可。
时间复杂度 ,其中 是题目给定的整数。空间复杂度 。
class Solution:
def subtractProductAndSum(self, n: int) -> int:
nums = list(map(int, str(n)))
return prod(nums) - sum(nums)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(d) where d is the number of digits in n, since each digit is processed once. Space complexity is O(1) because only two integer variables are used regardless of n's size. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask candidates to handle each digit efficiently without converting to arrays unnecessarily.
- question_mark
Check if the solution correctly initializes the product to 1 to avoid zeroing out the result.
- question_mark
Probe understanding of basic number manipulation and iteration over digits in an integer.
常见陷阱
外企场景- error
Initializing the product incorrectly as 0 instead of 1, causing the final result to always be zero.
- error
Skipping digits when using division and modulo incorrectly in the loop.
- error
Using excessive extra space instead of simple integer tracking for product and sum.
进阶变体
外企场景- arrow_right_alt
Compute the difference for very large integers requiring optimized iteration or string handling.
- arrow_right_alt
Return both product and sum separately instead of their difference for additional insight into digit composition.
- arrow_right_alt
Handle negative integers by considering absolute values or separate sign handling.