Difficulty: Easy | Acceptance: 53.70% | Paid: No Topics: String
Given an integer n, add a dot (”.”) as the thousands separator and return it in string format.
- Examples
- Constraints
- String Iteration
- Mathematical Extraction
- Recursion
Examples
Example 1
Input:
n = 987
Output:
"987"
Example 2
Input:
n = 1234
Output:
"1.234"
Constraints
0 <= n <= 2³¹ - 1
String Iteration
Intuition Convert the number to a string and iterate from the end, inserting a dot every three characters.
Steps
- Convert the integer to a string.
- Iterate through the string from right to left.
- Append characters to a result list.
- Insert a dot every time the count of processed characters is a multiple of 3 (and not the last character).
- Reverse the result list and join it into a string.
python
class Solution:
def thousandSeparator(self, n: int) -> str:
s = str(n)
res = []
for i, ch in enumerate(reversed(s)):
if i > 0 and i % 3 == 0:
res.append('.')
res.append(ch)
return ''.join(reversed(res))Complexity
- Time: O(log₁₀ n) - We iterate over the number of digits.
- Space: O(log₁₀ n) - To store the result string.
- Notes: Simple and readable, uses string manipulation.
Mathematical Extraction
Intuition Extract chunks of three digits from the right using modulo 1000 and integer division, then combine them.
Steps
- Handle the edge case where n is 0.
- While n is greater than 0, take n % 1000 to get the last three digits.
- Prepend this chunk to the result string.
- If there are remaining digits, prepend a dot.
- Divide n by 1000 to process the next chunk.
- Handle padding with zeros for chunks that are not the most significant (e.g., 1234 -> 1.234).
python
class Solution:
def thousandSeparator(self, n: int) -> str:
if n == 0:
return "0"
res = []
while n > 0:
chunk = n % 1000
n //= 1000
if n > 0:
res.append(str(chunk).zfill(3))
else:
res.append(str(chunk))
return '.'.join(reversed(res))Complexity
- Time: O(log₁₀ n) - We process the number digit by digit.
- Space: O(log₁₀ n) - To store the result string.
- Notes: Avoids converting the entire number to a string initially, working with math operations.
Recursion
Intuition Recursively process the number by removing the last three digits and appending them with a separator.
Steps
- Base case: if n is less than 1000, return the string representation of n.
- Recursive step: call the function on n / 1000.
- Append a dot and the last three digits (padded with zeros if necessary) to the result of the recursive call.
python
class Solution:
def thousandSeparator(self, n: int) -> str:
if n < 1000:
return str(n)
return self.thousandSeparator(n // 1000) + '.' + str(n % 1000).zfill(3)Complexity
- Time: O(log₁₀ n) - Each recursive call reduces the number of digits.
- Space: O(log₁₀ n) - Stack space for recursion and result string.
- Notes: Elegant solution, but uses implicit stack space.