KatInterview

Round Decimal Strings to a Power-of-Ten Step, No Floats

StringsModel answer
EasyModel answerStringsstringsroundingbig-numbers

Last updated

Round a decimal string to the nearest integer, then to a power-of-ten step such as 100 or 0.1, using only string and digit operations and a clearly stated tie-breaking rule.

You are given numbers as strings. They may be too long or too precise for a built-in float or fixed-width integer, so you must not convert the whole value to one. Do all the work on the characters.

Part 1: nearest integer

Write a function that takes a decimal string s and returns the nearest integer as a string.

  • s may start with + or -.
  • s may contain a single decimal point, and either side of it may be empty. For example, "-.2" means -0.2 and "2." means 2.0.
  • The integer part can have thousands of digits.
  • Exact halves (...5 exactly at the cut) need a rule. Choose a deterministic one, state it, and apply it consistently.

Part 2: nearest multiple of a step

Write a function that takes two strings:

  • s, a decimal number as above.
  • p, a positive step that is always a power of ten, such as "1000", "100", "0.1" or "0.01".

Return s rounded to the nearest multiple of p, as a string.

spresult
"12567""100""12600"
"1234.678""0.1""1234.7"

What to settle and show

  • Which inputs are valid, and what happens for invalid ones.
  • Your tie-breaking rule, and why it is convenient for negative numbers.
  • Your output format: leading zeros, a -0 result, and whether trailing zeros are kept when the step is fractional.
  • Time and space complexity.
  • Tests for carries (such as 999.9), tiny values, and steps larger than the number.

Hints

Hint 1

Part 1 is just Part 2 with a step of 1. Think of both as rounding to a multiple of 10^k, where k is the exponent of the step.

Hint 2

Remove the sign and glue the integer and fractional digits into one digit string. The decimal point is then a position (the length of the integer part), and the step decides how many leading digits you keep.

Hint 3

With round-half-away-from-zero you can round the magnitude and reattach the sign afterward. Only the first discarded digit matters: 5 or more means round up. Rounding up is a decimal increment with carry, where 999 becomes 1000 and an empty prefix becomes 1.

Hint 4

Handle the case where the step is larger than the number by treating the kept prefix as empty. Pad with zeros when the step is finer than the digits you have. Drop the sign if the result is zero.