FastPrepRound a Decimal String to Significant Digits

Round a Decimal String to Significant Digits

Google logoGoogle● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given a non-negative decimal number as a string number and a positive integer digits, round the number to that many significant decimal digits using round-half-up.

The input contains only digits and at most one decimal point. It has at least one digit and no sign or exponent. Leading and trailing zeroes may appear.

Return ordinary decimal notation with no decimal point when the rounded result is an integer. Otherwise remove trailing fractional zeroes. Return 0 when the value is zero.

Function

roundSignificant(number: String, digits: int) → String

Examples

Example 1

number = "124.23"digits = 2return = "120"

The first two significant digits are 1 and 2; the next digit is 4, so the result is 120.

Example 2

number = "0.009876"digits = 3return = "0.00988"

Leading zeroes are not significant, and the next digit rounds 987 upward.

Example 3

number = "999.5"digits = 3return = "1000"

Rounding propagates a carry into a new digit.

Constraints

  • 1 <= number.length <= 200000.
  • 1 <= digits <= 200000.
  • The input is a valid non-negative decimal string with at most one decimal point.

More Google problems

See Google hiring insights
public String roundSignificant(String number, int digits) {
    // Write your code here.
}
number"124.23"
digits2
expected"120"
Checking account…