Problem

Given an integer n, add a dot (".") as the thousands separator and return it in string format.

Examples

Example 1

1
2
3
4
5
6

    
    
    Input: n = 987
    Output: "987"
    

Example 2

1
2
3
4
5
6

    
    
    Input: n = 1234
    Output: "1.234"
    

Constraints

  • 0 <= n <= 2^31 - 1

Solution

Method 1 - String Manipulation from End

Convert the number to a string, then insert dots every three digits from the right.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <string>
using namespace std;
class Solution {
public:
    string thousandSeparator(int n) {
        string s = to_string(n), res;
        int cnt = 0;
        for (int i = s.size()-1; i >= 0; --i) {
            if (cnt && cnt % 3 == 0) res = '.' + res;
            res = s[i] + res;
            ++cnt;
        }
        return res;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    public String thousandSeparator(int n) {
        String s = Integer.toString(n);
        StringBuilder sb = new StringBuilder();
        int cnt = 0;
        for (int i = s.length() - 1; i >= 0; --i) {
            if (cnt > 0 && cnt % 3 == 0) sb.append('.');
            sb.append(s.charAt(i));
            cnt++;
        }
        return sb.reverse().toString();
    }
}
1
2
3
4
5
6
7
8
9
class Solution:
    def thousandSeparator(self, n: int) -> str:
        s = str(n)
        res = []
        for i, c in enumerate(reversed(s)):
            if i and i % 3 == 0:
                res.append('.')
            res.append(c)
        return ''.join(reversed(res))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
impl Solution {
    pub fn thousand_separator(n: i32) -> String {
        let s = n.to_string();
        let mut res = String::new();
        let mut cnt = 0;
        for c in s.chars().rev() {
            if cnt > 0 && cnt % 3 == 0 {
                res.push('.');
            }
            res.push(c);
            cnt += 1;
        }
        res.chars().rev().collect()
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function thousandSeparator(n: number): string {
    const s = n.toString();
    let res = '';
    let cnt = 0;
    for (let i = s.length - 1; i >= 0; --i) {
        if (cnt > 0 && cnt % 3 === 0) res = '.' + res;
        res = s[i] + res;
        cnt++;
    }
    return res;
}

Complexity

  • ⏰ Time complexity: O(log_{10} n)
  • 🧺 Space complexity: O(log_{10} n)