Thousand Separator Problem
#1556
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1556.
Given an integer n, add a dot (".") as the thousands separator and return it in string format.
Example 1:
Input: n = 987
Output: "987"
Example 2:
Input: n = 1234
Output: "1.234"
Constraints:
0 <= n <= 2^31 - 1
Solution
Approach: Insert a Dot Every Three Digits from the Right
Convert n to its decimal string digits and copy it character by character. Groups are counted from the right, so a dot goes in front of position i exactly when the number of digits from i to the end, len - i, is a multiple of three, and i > 0 so the result never starts with a dot.
For example, 1234567 has length 7: dots go before positions 1 and 4, giving 1.234.567. Numbers with at most three digits, including 0, come back unchanged.
Complexity: O(d) time and space, where d is the number of digits (at most 10).
class Solution:
def thousandSeparator(self, n: int) -> str:
digits = str(n)
parts = []
# Walk from the right in steps of three; the leftmost group may be shorter.
end = len(digits)
while end > 0:
parts.append(digits[max(0, end - 3):end])
end -= 3
return ".".join(reversed(parts))