LeetCode 题解工作台

交替数字和

给你一个正整数 n 。 n 中的每一位数字都会按下述规则分配一个符号: 最高有效位 上的数字分配到 正 号。 剩余每位上数字的符号都与其相邻数字相反。 返回所有数字及其对应符号的和。 示例 1: 输入: n = 521 输出: 4 解释: (+5) + (-2) + (+1) = 4 示例 2: 输…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

直接根据题目描述模拟即可。 我们定义一个初始符号 ,然后从最高有效位开始,每次取出一位数字 ,与 相乘,将结果加到答案中,然后将 取反,继续处理下一位数字,直到处理完所有数字。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数 nn 中的每一位数字都会按下述规则分配一个符号:

  • 最高有效位 上的数字分配到 号。
  • 剩余每位上数字的符号都与其相邻数字相反。

返回所有数字及其对应符号的和。

 

示例 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

 

lightbulb

解题思路

方法一:模拟

直接根据题目描述模拟即可。

我们定义一个初始符号 sign=1sign=1,然后从最高有效位开始,每次取出一位数字 xx,与 signsign 相乘,将结果加到答案中,然后将 signsign 取反,继续处理下一位数字,直到处理完所有数字。

时间复杂度 O(logn)O(\log n),空间复杂度 O(logn)O(\log n)。其中 nn 为给定数字。

1
2
3
4
class Solution:
    def alternateDigitSum(self, n: int) -> int:
        return sum((-1) ** i * int(x) for i, x in enumerate(str(n)))
speed

复杂度分析

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

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

交替数字和题解:数学·driven | LeetCode #2544 简单