FastPrepInteger Square Root with Error Checks

Integer Square Root with Error Checks

Bloomberg LP logoBloomberg LP● EasyNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Return floor(sqrt(x)) when x is nonnegative. Return -1 when x is negative.

Do not use a library square-root function, and avoid overflow when comparing a candidate square with x.

Function

integerSqrt(x: int) → int

Examples

Example 1

x = 8return = 2

The square root is between 2 and 3, so its floor is 2.

Example 2

x = -4return = -1

Negative input uses the documented sentinel.

Constraints

  • -2^31 <= x <= 2^31 - 1.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int integerSqrt(int x) {
  // Write your code here.
}
x8
expected2
Checking account…