DevPath

← All problems

Integer Square Root

Easy math · binary-search

Description

Return the floor of the square root of a non-negative integer.

Constraints

0 <= n <= 10^12

Examples

Input: n = 8

Output: 2

Hints (1)
  • Binary search for the largest k with k*k <= n.

Solutions

Binary search. · Time O(log n) · Space O(1)

func intSqrt(n int) int {
    if n < 2 {
        return n
    }
    lo, hi, ans := 1, n/2, 0
    for lo <= hi {
        mid := (lo + hi) / 2
        if mid*mid <= n {
            ans = mid
            lo = mid + 1
        } else {
            hi = mid - 1
        }
    }
    return ans
}

Create a free account to submit solutions, track progress and save problems.

Create account