经典算法题:给出一个正整数,需要将数字千分位格式化,输出字符串。
一、问题示例 示例 1:
输入:3134250234 输出:3,134,250,234 示例 2:
二、代码演示 数字千分位格式 数组反转 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 export function format1 (n: number ): string { n = Math .floor (n) const s = `${n} ` const arr = s.split ('' ).reverse () return arr.reduce ((prev, val, index ) => { if (index % 3 === 0 ) { if (prev) { return val + ',' + prev } else { return val } } else { return val + prev } }, '' ) }
数字千分位格式化 字符串分析 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 export function format2 (n: number ):string { n = Math .floor (n) let res = '' const s = n.toString () const len = s.length for (let i = len - 1 ; i >= 0 ; i--) { const j = len - i if (j % 3 === 0 ) { if (i === 0 ) { res = s[i] + res } else { res = ',' + s[i] + res } } else { res = s[i] + res } } return res }
三、单元测试 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 import { format1, format2 } from '../thousands-format.ts' describe ('数字千分位格式化 数组反转' , () => { it ('正常情况' , () => { const n = 1241475429 const res = format1 (n) expect (res).toBe ('1,241,475,429' ) }) it ('小于 1000' , () => { expect (format1 (0 )).toBe ('0' ) expect (format1 (122 )).toBe ('122' ) }) })describe ('数字千分位格式化 字符串分析' , () => { it ('正常情况' , () => { const n = 1241475429 const res = format2 (n) expect (res).toBe ('1,241,475,429' ) }) it ('小于 1000' , () => { expect (format2 (0 )).toBe ('0' ) expect (format2 (122 )).toBe ('122' ) }) })
四、算法复杂度 两种方法整体复杂度都是 O(n),但是 方法1 使用数组,转换、操作会影响性能,因此使用 字符串 性能更好。
欢迎访问:天问博客