HPE VO Interview Coding Question: Truncated Integer Square Root

18 Views
No Comments

Given a non-negative integer a, compute and return the truncated integer of the square root of a.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(), 0.5, or a ** 0.5.

Example 1:

Input: a = 4
Output: 2

Example 2:

Input: a = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.

Constraints:

0 <= a <= 2**31 - 1

This problem asks for the floor of the square root of a non-negative integer without using built-in power or square-root operations. The standard solution is binary search over the range [0, a], maintaining the largest value whose square is less than or equal to a. This avoids floating-point precision issues and runs efficiently for the full 32-bit integer range. For example, 4 returns 2, and 8 also returns 2 because its square root is 2.82842…, which truncates to 2.

END
 0