KatInterview

Group Digits of a Signed Integer with a Custom Delimiter

StringsAuto-graded · 23 test cases
MediumAuto-gradedStringsstringsmathformatting

Last 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 value is 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(), the format() function, or locale utilities.

Function

Implement group_digits(value, delimiter) that returns the formatted string.

Constraints

  • -2^63 <= value <= 2^63 - 1
  • delimiter is a single ASCII character, for example ',', '.', or '_'.
  • Running time should be O(d), where d is the number of digits of value.
  • 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.