LeetCode 1556. 千位分隔数

题目描述

1556. 千位分隔数

思路分析

解法一:从右到左插入分隔符(推荐)

核心思路

  • 将数字转为字符串,从右向左遍历。
  • 每处理 3 位插入一个 .,最后反转得到结果。


复杂度分析

  • 时间复杂度:O(k),其中 k 表示数字位数。
  • 空间复杂度:O(k)。
// 从右到左插入分隔符
class Solution {
    public String thousandSeparator(int n) {
        if (n == 0) {
            return "0";
        }

        StringBuilder sb = new StringBuilder();
        int count = 0;
        while (n > 0) {
            if (count == 3) {
                sb.append('.');
                count = 0;
            }
            sb.append(n % 10);
            n /= 10;
            count++;
        }
        return sb.reverse().toString();
    }
}
// 从右到左插入分隔符
func thousandSeparator(n int) string {
	if n == 0 {
		return "0"
	}

	res := make([]byte, 0)
	count := 0
	for n > 0 {
		if count == 3 {
			res = append(res, '.')
			count = 0
		}
		res = append(res, byte('0'+n%10))
		n /= 10
		count++
	}

	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return string(res)
}

相似题目

题目 难度 考察点
67. 二进制求和 简单 字符串模拟
415. 字符串相加 简单 字符串模拟
43. 字符串相乘 中等 字符串模拟
168. Excel 表列名称 简单 进制转换
171. Excel 表列序号 简单 进制转换
224. 基本计算器 困难
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/19972271
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!