Thousand Separator
Problem
Given an integer n, add a dot '.' as the thousands separator and return it as a string. The dot goes between every group of three digits counted from the right.
n = 1234567"1.234.567"def thousand_separator(n):
s = str(n)
out = []
count = 0
for ch in reversed(s):
if count and count % 3 == 0:
out.append(".")
out.append(ch)
count += 1
return "".join(reversed(out))
function thousandSeparator(n) {
const s = String(n);
let out = "";
let count = 0;
for (let i = s.length - 1; i >= 0; i--) {
if (count && count % 3 === 0) out = "." + out;
out = s[i] + out;
count++;
}
return out;
}
class Solution {
public String thousandSeparator(int n) {
String s = Integer.toString(n);
StringBuilder out = new StringBuilder();
int count = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (count > 0 && count % 3 == 0) out.append('.');
out.append(s.charAt(i));
count++;
}
return out.reverse().toString();
}
}
string thousandSeparator(int n) {
string s = to_string(n);
string out = "";
int count = 0;
for (int i = s.size() - 1; i >= 0; i--) {
if (count && count % 3 == 0) out = '.' + out;
out = s[i] + out;
count++;
}
return out;
}
Explanation
Thousand separators group digits in threes starting from the right, because the rightmost group (the ones, tens, hundreds) is always full while the leftmost group may be short. So the natural direction to scan is right to left.
We convert the number to its digit string and walk from the last character to the first, keeping a count of how many digits we have already placed.
Before placing each digit, we ask: have we just completed a group of three? That is true when count is non-zero and divisible by 3. If so, we insert a '.' first, then the digit.
Because we are building the answer from the right, we either prepend each piece (JS/C++) or collect into a list and reverse at the end (Python/Java). The count > 0 guard prevents a stray leading dot when the total length is an exact multiple of three.
Example: 1234567. Scanning 7,6,5 then a dot, 4,3,2 then a dot, then 1 gives "1.234.567".