algoadvance

Given an integer n, return a string representation of this integer with commas as the thousand separators.

Example 1:

Input: n = 987
Output: "987"

Example 2:

Input: n = 1234
Output: "1.234"

Clarifying Questions

  1. Q: What is the range of the integer n? A: n can range from 0 to all possible integer values in Python, but typically we would expect non-negative integers.

  2. Q: Is any specific format required when the integer is zero? A: 0 should simply be represented as "0" with no additional formatting needed.

  3. Q: Are negative numbers expected in the input? A: Based on typical scenarios for this problem, we assume only non-negative integers are expected unless otherwise specified.

Strategy

To solve this problem efficiently, we can utilize Python string manipulation:

  1. Convert the integer to a string.
  2. Reverse the string to group digits easily.
  3. Insert a dot '.' every three digits while iterating through the reversed string.
  4. Reverse the result again to get the final formatted string.

Code

Here is the Python function to solve the problem:

def thousandSeparator(n: int) -> str:
    s = str(n)[::-1]
    parts = [s[i:i+3] for i in range(0, len(s), 3)]
    return '.'.join(parts)[::-1]

# Example Usage:
print(thousandSeparator(987))   # Output: "987"
print(thousandSeparator(123456789))   # Output: "123.456.789"
print(thousandSeparator(1000))    # Output: "1.000"

Explanation

  1. Convert integer to string and reverse:
    • str(n)[::-1] converts the integer to a string and reverses it.
  2. Split reversed string into 3-char parts:
    • [s[i:i+3] for i in range(0, len(s), 3)] uses a list comprehension to split the reversed string into parts of length 3.
  3. Join parts with dot and reverse again:
    • '.'.join(parts)[::-1] joins the parts with dots and then reverses the resultant string to get the final output.

Time Complexity

This solution is efficient and should handle large integers within typical constraints comfortably.

Try our interview co-pilot at AlgoAdvance.com