yanggengzhen123 / leetcode-group

力扣小组
0 stars 0 forks source link

2022.04.19-第83题-1556. 千位分隔数 #85

Open icodeish opened 2 years ago

icodeish commented 2 years ago

https://leetcode-cn.com/problems/thousand-separator/ 给你一个整数 n,请你每隔三位添加点(即 "." 符号)作为千位分隔符,并将结果以字符串格式返回。 示例 1:

输入:n = 987 输出:"987" 示例 2:

输入:n = 1234 输出:"1.234" 示例 3:

输入:n = 123456789 输出:"123.456.789" 示例 4:

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

icodeish commented 2 years ago
function thousandSeparator(n) {
    if (n === 0) return '0'
    let res = []
    n = n.toString().split('').reverse().join('')
    for (let i = 0; i < n.length; i++) {
        res.push(n[i])
        if ((i + 1) % 3 === 0) res.push('.')
    }
    return n.length % 3 === 0 ? res.reverse().join().replace(/,/g, "").substring(1) : res.reverse().join().replace(/,/g, "")
}
yanggengzhen123 commented 2 years ago
function thousandSeparator(n: number): string {
   let arr:string[] = []
   let count:number = 0
   for(let i = n.toString().length - 1;i >= 0;i--){
       if(count === 3){
            arr.unshift('.')
            count = 0
       }
       arr.unshift(n.toString()[i])
       count++
   }
   return arr.join('')
};