We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Thousand Separator

Number: 1660

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a non-negative integer n, convert it to a string and insert a dot “.” as the thousands separator. For example, 1234 becomes "1.234" and 987 remains "987".


Key Insights

  • Convert the integer to its string representation.
  • Process the string from right to left to group digits in sets of three.
  • Insert a dot between these groups.
  • Reverse the result to restore the original digit order.

Space and Time Complexity

Time Complexity: O(n) where n is the number of digits
Space Complexity: O(n) for storing the new string with separators


Solution

We first convert the given number to a string. Then, starting from the end of the string, we group the digits in batches of three. For each complete group (except possibly the first), a dot is added as a separator. Finally, we reverse the built string to obtain the thousands-separated number in correct order. This approach efficiently handles the grouping without converting back and forth from numeric types.


Code Solutions

# Define the function to format the number with a thousands separator
def thousandSeparator(n):
    # Convert the integer to string for easier manipulation
    s = str(n)
    # Initialize an empty list to build the result in reverse order
    parts = []
    # Counter for digits processed in the current group
    count = 0
    # Iterate over the string in reverse order
    for digit in s[::-1]:
        parts.append(digit)  # Append the current digit
        count += 1
        # If three digits have been processed and there are still digits remaining, add a dot separator
        if count == 3 and len(parts) < len(s) + (len(s) - 1) // 3:
            parts.append('.')
            count = 0  # Reset count after inserting separator
    # Reverse the list to restore the original order and join the list into a string
    return ''.join(parts[::-1])

# Example usage:
print(thousandSeparator(987))   # Output: "987"
print(thousandSeparator(1234))  # Output: "1.234"
← Back to All Questions