Implement string-based rounding without floats
PinterestMachine Learning Engineer · Technical ScreenLast updated
This question evaluates proficiency in string-based numeric processing, arbitrary-precision arithmetic concepts, precise rounding rules including deterministic tie-breaking, and handling of sign and decimal edge cases, and falls under the Coding & Algorithms domain.
Coding
You are not allowed to parse the input into a built-in floating type (to avoid overflow and precision issues). Work directly on strings.
1) Implement round(s) from scratch
Given a string s representing a decimal number, return a string representing the value rounded to the nearest integer.
smay include an optional sign (+/-) and an optional decimal point.- Examples of tricky inputs you must handle:
"-.2"(equivalent to-0.2)"2."(equivalent to2.0)- Very long integer parts that would overflow
float()
Clarify and implement a deterministic tie-breaking rule (e.g., exactly .5 cases).
2) Round a numeric string s to a given precision p
Given two strings:
s: a decimal number as a stringp: a positive decimal precision as a string
Return s rounded to the nearest multiple of p (as a string).
Examples:
s = "12567",p = "100"→ return"12600"s = "1234.678",p = "0.1"→ return"1234.7"
Assume p is a power of 10 (e.g., 1000, 0.01, 0.1). Specify how you format the output (e.g., whether to keep trailing zeros).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.