Skip to content
On this page

69. Sqrt(x) share

Problem Statement

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

 

Example 1:

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.

 

Constraints:

  • 0 <= x <= 231 - 1
Click to open Hints
  • Try exploring all integers. (Credits: @annujoshi)
  • Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)

Solution:

go
package main

func mySqrt(x int) int {
	start := 0
	end := x

	for start < end {
		// this is to floor the mid value
		// mid of 8 will be 4 , (8+1)/2 = 4.5
		// mid of 9 will be 5 , (9+1)/2 = 5
		mid := start + (end-start+1)/2
		if mid*mid > x {
			end = mid - 1
		} else {
			start = mid
		}
	}

	return end
}

...


Released under the MIT License.