LeetCode 题解工作台
交替数字和
给你一个正整数 n 。 n 中的每一位数字都会按下述规则分配一个符号: 最高有效位 上的数字分配到 正 号。 剩余每位上数字的符号都与其相邻数字相反。 返回所有数字及其对应符号的和。 示例 1: 输入: n = 521 输出: 4 解释: (+5) + (-2) + (+1) = 4 示例 2: 输…
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
直接根据题目描述模拟即可。 我们定义一个初始符号 ,然后从最高有效位开始,每次取出一位数字 ,与 相乘,将结果加到答案中,然后将 取反,继续处理下一位数字,直到处理完所有数字。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
给你一个正整数 n 。n 中的每一位数字都会按下述规则分配一个符号:
- 最高有效位 上的数字分配到 正 号。
- 剩余每位上数字的符号都与其相邻数字相反。
返回所有数字及其对应符号的和。
示例 1:
输入:n = 521 输出:4 解释:(+5) + (-2) + (+1) = 4
示例 2:
输入:n = 111 输出:1 解释:(+1) + (-1) + (+1) = 1
示例 3:
输入:n = 886996 输出:0 解释:(+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0
提示:
1 <= n <= 109
解题思路
方法一:模拟
直接根据题目描述模拟即可。
我们定义一个初始符号 ,然后从最高有效位开始,每次取出一位数字 ,与 相乘,将结果加到答案中,然后将 取反,继续处理下一位数字,直到处理完所有数字。
时间复杂度 ,空间复杂度 。其中 为给定数字。
class Solution:
def alternateDigitSum(self, n: int) -> int:
return sum((-1) ** i * int(x) for i, x in enumerate(str(n)))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(d) where d is the number of digits in n because each digit is processed once. Space complexity is O(d) if using an array of digits, or O(1) if processing digits in place without extra storage. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Mentions looping through digits explicitly.
- question_mark
Asks about sign alternation and edge cases like single-digit numbers.
- question_mark
Checks if you can optimize space without losing clarity.
常见陷阱
外企场景- error
Forgetting to start with positive for the first digit.
- error
Incorrectly flipping signs when iterating over digits.
- error
Assuming integer math alone without converting to accessible digit form.
进阶变体
外企场景- arrow_right_alt
Compute alternating sum starting from the least significant digit.
- arrow_right_alt
Apply different sign patterns such as ++-- repeating for every four digits.
- arrow_right_alt
Calculate modulo result of alternating digit sum for very large n.