2020年4月27日

数字千分位格式化

问题描述

实现一个函数,将数字格式化为带有千分位分隔符的字符串,只考虑正整数。

要求

  1. 支持正负整数
  2. 从右向左每三位添加逗号分隔符
  3. 时间复杂度O(n),空间复杂度O(1)

示例

输入: 1234567
输出: "1,234,567"

解题思路

/**
 * 将数值格式化为从右向左每三位加逗号的字符串
 * @param millimeters 输入的数值
 * @returns 格式化后的字符串(从个位开始每三位加逗号)
 * 
 * 示例:
 * formatMillimeters(1234567) => "7,654,321"
 * formatMillimeters(1000) => "0,001"
 */
export function formatMillimeters(millimeters: number): string {
    // 取整处理,确保只处理整数部分
    let n = Math.floor(millimeters);

    // 将数字转为字符串
    const a = n + "";

    // 定义一个空字符串用于存储结果

    let res = "";
    console.log("a is:", a);
    for (let i = a.length - 1; i >= 0; i--) {
        let offset = a.length - i;
        if (offset % 3 === 0 && i !== a.length - 1 && i !== 0) {
            res = "," + a[i] + res;
        } else {
            res = a[i] + res;
        }

    }

    return res;
};

/**
 * 将数值格式化为标准千位分隔符字符串(从左向右)
 * @param millimeters 输入的数值
 * @returns 格式化后的字符串(从左向右每三位加逗号)
 * 
 * 示例:
 * formatMillimetersByString(1234567) => "1,234,567"
 * formatMillimetersByString(1000) => "1,000"
 */
export function formatMillimetersByString(millimeters: number): string {
    // 取整处理,确保只处理整数部分
    let n = Math.floor(millimeters);
    
    // 将数字转为字符串
    const a = n + "";
    
    // 初始化结果字符串
    let res = "";
    const length = a.length;
    // 从右向左遍历字符串
    for (let i = length - 1; i >= 0; i--) {
        // 计算当前字符距离字符串末尾的偏移量
        let offset = length - i;
        // 每三位添加逗号(排除第一位和最后一位)
        if (offset % 3 === 0 && i !== length - 1 && i !== 0) {
            res = "," + a[i] + res; // 添加逗号分隔符
        } else {
            res = a[i] + res; // 直接添加数字字符
        }
    }
    
    return res;
};
Share