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"
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.
Q: Is any specific format required when the integer is zero?
A: 0 should simply be represented as "0" with no additional formatting needed.
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.
To solve this problem efficiently, we can utilize Python string manipulation:
'.' every three digits while iterating through the reversed string.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"
str(n)[::-1] converts the integer to a string and reverses it.[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.'.'.join(parts)[::-1] joins the parts with dots and then reverses the resultant string to get the final output.O(n), where n is the number of digits in the integer. Each step (reversing the string, splitting into parts, joining, and reversing back) is linear in terms of the number of digits.O(n), for storing the intermediate results (reversed string, parts list, and the final string).This solution is efficient and should handle large integers within typical constraints comfortably.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?