Thousand Separator
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an integer n, add a dot (".") as the thousands separator and return it in string format.
Examples
Example 1
Input: n = 987
Output: "987"
Example 2
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
C++
#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;
}
};
Java
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();
}
}
Python
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))
Rust
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()
}
}
TypeScript
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)