Group Digits of a Signed Integer with a Custom Delimiter
StringsAuto-graded · 23 test casesLast updated
Build a string from a signed 64-bit integer, placing a delimiter between each group of three digits from the right, with the minus sign kept in front, using manual digit handling.
Digit Grouping
You are given a signed 64-bit integer value and a one-character delimiter delimiter. Produce the decimal text of value in which the digits are split into groups of three, counting from the rightmost digit, and consecutive groups are joined by delimiter.
Rules:
- The leftmost group may contain 1, 2, or 3 digits; every other group contains exactly 3 digits.
- The delimiter appears only between two groups. It never appears at the start or at the end of the digits.
- If
valueis negative, a single-is placed at the very start of the result. It is attached directly to the first digit, with no delimiter between them. - A value with three digits or fewer has no delimiter at all.
- Zero is written as
"0". - Do not use built-in number formatting facilities such as
f"{value:,}",str.format(), theformat()function, or locale utilities.
Function
Implement group_digits(value, delimiter) that returns the formatted string.
Constraints
-2^63 <= value <= 2^63 - 1delimiteris a single ASCII character, for example',','.', or'_'.- Running time should be
O(d), wheredis the number of digits ofvalue. - Extra space should be
O(d).
Examples
Example 1
Input: group_digits(1234567, ',')
Output: '1,234,567'
Example 2
Input: group_digits(-9876543210, '.')
Output: '-9.876.543.210'
Example 3
Input: group_digits(0, ',')
Output: '0'
Hints
Hint 1
Handle the sign separately: remember whether the number is negative, then work only with its magnitude, and add the minus sign at the very end.
Hint 2
You can get digits one at a time with `% 10` and `// 10`. They come out least-significant first, so reverse them afterwards. Remember that zero needs its own case.
Hint 3
To avoid a leading delimiter, compute the size of the first group as `len(digits) % 3`, using 3 if that is 0. After that, every remaining group has exactly three digits.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the work into two small steps: get the digits, then group them.
- Note whether
valueis negative and continue with its magnitude only. - If the magnitude is zero, the digit list is just
["0"]. Otherwise repeatedly takemagnitude % 10as the next digit, convert it to a character withchr(ord("0") + digit), and divide the magnitude by 10. Digits come out least-significant first, so reverse the list. - Grouping from the right is equivalent to grouping from the left once the size of the first group is known. With
ddigits, the first group hasd % 3digits, or 3 if that remainder is 0. After it, the remaining digit count is a multiple of 3, so the rest can be cut into chunks of exactly three. - Join the chunks with the delimiter, then prepend
-if the original value was negative.
Why it is correct
- Each loop step emits the current lowest digit and removes it, so the loop yields exactly the decimal digits of the magnitude in reverse; reversing restores the order.
- The first group size
fsatisfies1 <= f <= 3andd - fis divisible by 3, so every later chunk has exactly three digits. This is the same as grouping in threes from the right. delimiter.join(parts)puts the delimiter only between parts, so there is never a leading or trailing delimiter, and numbers with at most three digits produce a single part.- The minus sign is added after joining, so it stays at the very front and is never separated from the first digit.
- Python integers do not overflow, so negating
-2^63is safe.
Complexity
- Time:
O(d), withd <= 19for 64-bit values; every step touches each digit a constant number of times. - Space:
O(d)for the digit list, the parts, and the output.
Reference solution
def group_digits(value, delimiter=","):
negative = value < 0
magnitude = -value if negative else value
if magnitude == 0:
digits = ["0"]
else:
digits = []
while magnitude > 0:
digits.append(chr(ord("0") + magnitude % 10))
magnitude //= 10
digits.reverse()
first_size = len(digits) % 3 or 3
parts = ["".join(digits[:first_size])]
for i in range(first_size, len(digits), 3):
parts.append("".join(digits[i:i + 3]))
result = delimiter.join(parts)
return ("-" if negative else "") + result