Round numeric string values
Company: Pinterest
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates parsing and numeric manipulation skills, specifically implementing rounding rules for numeric strings and handling decimals, significant digits, and precision edge cases.
Constraints
- 1 <= len(s) <= 100000
- s matches the regex ^[+-]?\d+(\.\d+)?$ (no exponent, no separators)
- mode is either "integer" or "last_sig_digit"
- Rounding rule for mode="integer": nearest integer, ties at .5 round away from zero
- Rounding rule for mode="last_sig_digit": half-up on the last significant digit; if only one significant digit exists, return canonical s
- Output formatting: remove leading zeros (keep one before '.'), remove trailing zeros after '.', remove trailing '.', never return "-0"
Examples
Input:
Expected Output: 4
Input:
Expected Output: 100
Hints
- Avoid floating-point; work directly on the string digits.
- For integer rounding, comparing only the first digit after the decimal to 5 suffices to decide <0.5 vs >=0.5.
- Represent the number as a digit array plus the decimal index. For last_sig_digit, find the first and last non-zero positions.
- When reducing precision by one significant digit, round the digit before the last non-zero and propagate carry left; then zero-out all less significant digits.
- Normalize the final string: strip leading zeros in the integer part (keep one zero), strip trailing zeros in the fractional part, and omit the decimal point if the fractional part becomes empty.