Thousand Separator - Problem

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

The thousands separator should be placed every three digits from the right.

Examples:

  • 1234 becomes "1.234"
  • 987654321 becomes "987.654.321"
  • 123 becomes "123" (no separator needed)

Input & Output

Example 1 — Basic Case
$ Input: n = 987
Output: "987"
💡 Note: Number has 3 digits, so no separator needed
Example 2 — Four Digits
$ Input: n = 1234
Output: "1.234"
💡 Note: Insert dot after first digit: 1 and 234
Example 3 — Large Number
$ Input: n = 123456789
Output: "123.456.789"
💡 Note: Two dots needed: 123, 456, and 789 are each 3-digit groups

Constraints

  • 0 ≤ n ≤ 231 - 1

Visualization

Tap to expand
Thousand Separator INPUT Integer n 987 Digit Analysis: 9 pos 2 8 pos 1 7 pos 0 Total digits: 3 (less than 4) No separator needed! ALGORITHM STEPS 1 Convert to String n = 987 becomes "987" 2 Count Digits Length = 3 3 Check Position Every 3rd from right 4 Add Separator Insert "." if needed Position Check (from right) pos 0: 7 0 % 3 != 0 pos 1: 8 1 % 3 != 0 pos 2: 9 2 % 3 != 0 FINAL RESULT Output String "987" Comparison Input 987 --> Output "987" Why no dot? 987 has only 3 digits Separator needed at 4+ digits e.g., 1.000 or 1.234.567 Key Insight: The thousands separator "." is placed every 3 digits from the RIGHT. For numbers with 3 or fewer digits (like 987), no separator is needed. Direct construction builds the result by checking position % 3 == 0. TutorialsPoint - Thousand Separator | Direct Construction Approach
Asked in
Google 15 Amazon 12 Microsoft 10
28.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen