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 <= 231 - 1
This problem requires formatting an integer with thousands separators (dots). The solutions presented use a similar approach: iterating through the digits of the integer from right to left, adding a dot every three digits.
Approach:
Reverse Iteration: The solutions efficiently process the integer by iterating through its digits from right to left (least significant to most significant). This avoids the need for string manipulation or array reversal at the end.
Modulo and Division: The %
(modulo) operator extracts the last digit, and the /=
(integer division) removes the last digit. This process repeats until all digits are processed.
Counter and Dot Insertion: A counter (cnt
) keeps track of the number of digits processed since the last dot. When the counter reaches 3, a dot (.
) is added to the result.
String Building: The digits and dots are appended to a string builder (or list in Python) in reverse order. Finally, the string builder is reversed to get the correctly ordered result.
Time and Space Complexity Analysis:
Time Complexity: O(log₁₀(n)). The number of iterations is proportional to the number of digits in the integer n
, which is logarithmic with base 10.
Space Complexity: O(log₁₀(n)). The space used is proportional to the number of digits in the integer, which is logarithmic. This accounts for the space used to store the result string or list.
Code Explanation (Python):
The Python solution exemplifies the approach:
class Solution:
def thousandSeparator(self, n: int) -> str:
cnt = 0
ans = []
while 1:
n, v = divmod(n, 10) # Get the last digit (v) and remove it from n
ans.append(str(v)) # Add the digit to the result list
cnt += 1 # Increment the counter
if n == 0: # Base case: all digits processed
break
if cnt == 3: # Add a dot every three digits
ans.append('.')
cnt = 0
return ''.join(ans[::-1]) # Reverse and join the list to form the string
The other languages (Java, C++, Go) follow a very similar structure, adapting the syntax to each language but maintaining the core algorithm's logic. For instance, Java uses StringBuilder
for efficient string manipulation. C++ utilizes string
and reverse()
for string manipulation. Go uses byte slices and manual reversing. All maintain the same logarithmic time and space complexity.