LeetCode 题解工作台

整数的各位积和之差

给你一个整数 n ,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。 示例 1: 输入: n = 234 输出: 15 解释: 各位数之积 = 2 * 3 * 4 = 24 各位数之和 = 2 + 3 + 4 = 9 结果 = 24 - 9 = 15 示例 2: 输入: n = 44…

category

1

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

我们用两个变量 和 分别记录各位数之积、各位数之和,初始时 。 当 $n \gt 0$ 时,每次将 对 取模得到当前位的数字 ,并将 除以 后继续进行下一次循环。在每次循环中,我们更新 $x = x \times v$, $y = y + v$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数 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
lightbulb

解题思路

方法一:模拟

我们用两个变量 xxyy 分别记录各位数之积、各位数之和,初始时 x=1,y=0x=1,y=0

n>0n \gt 0 时,每次将 nn1010 取模得到当前位的数字 vv,并将 nn 除以 1010 后继续进行下一次循环。在每次循环中,我们更新 x=x×vx = x \times v, y=y+vy = y + v

最终,我们返回 xyx - y 即可。

时间复杂度 O(logn)O(\log n),其中 nn 是题目给定的整数。空间复杂度 O(1)O(1)

1
2
3
4
5
class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        nums = list(map(int, str(n)))
        return prod(nums) - sum(nums)
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

整数的各位积和之差题解:数学·driven | LeetCode #1281 简单