LeetCode 题解工作台

千位分隔数

给你一个整数 n ,请你每隔三位添加点(即 "." 符号)作为千位分隔符,并将结果以字符串格式返回。 示例 1: 输入: n = 987 输出: "987" 示例 2: 输入: n = 1234 输出: "1.234" 示例 3: 输入: n = 123456789 输出: "123.456.789…

category

1

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

直接按照题目要求模拟即可。 时间复杂度 $O(\log n)$,忽略答案的空间消耗,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数 n,请你每隔三位添加点(即 "." 符号)作为千位分隔符,并将结果以字符串格式返回。

 

示例 1:

输入:n = 987
输出:"987"

示例 2:

输入:n = 1234
输出:"1.234"

示例 3:

输入:n = 123456789
输出:"123.456.789"

示例 4:

输入:n = 0
输出:"0"

 

提示:

  • 0 <= n < 2^31
lightbulb

解题思路

方法一:模拟

直接按照题目要求模拟即可。

时间复杂度 O(logn)O(\log n),忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def thousandSeparator(self, n: int) -> str:
        cnt = 0
        ans = []
        while 1:
            n, v = divmod(n, 10)
            ans.append(str(v))
            cnt += 1
            if n == 0:
                break
            if cnt == 3:
                ans.append('.')
                cnt = 0
        return ''.join(ans[::-1])
speed

复杂度分析

指标
时间complexity is O(log n) because the number of digits in n is proportional to log(n). Space complexity is also O(log n) to store the intermediate string and reconstructed output with separators.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Pay attention to scanning direction; starting from the wrong end can misplace separators.

  • question_mark

    Watch for edge cases where n < 1000, as no separators should be added.

  • question_mark

    Confirm that the solution does not modify the numeric value, only its string representation.

warning

常见陷阱

外企场景
  • error

    Inserting separators from left to right without counting groups can create extra dots.

  • error

    Failing to handle numbers less than 1000 may produce incorrect output.

  • error

    Neglecting to reverse the string after inserting separators from the end leads to misaligned formatting.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Use commas ',' instead of dots '.' for different locale formatting.

  • arrow_right_alt

    Apply the separator pattern to floating-point numbers by splitting integer and fractional parts.

  • arrow_right_alt

    Implement a recursive solution that formats the number by repeatedly processing blocks of three digits.

help

常见问题

外企场景

千位分隔数题解:String-driven solution … | LeetCode #1556 简单