NOTE

Square Root

Implement the function int sqrt(int x). Compute and return the square root of x, rounded down.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Implement the function int sqrt(int x). Compute and return the square root of x, rounded down.

2. Approach

  1. Approach 1
    • Traverse [1,x]
    • The current number is less than the target and the next number is greater than the target
  2. Approach 2
    • Binary search

3. Implementation

3.1. Traversal

func mySqrt(x int) int {

	for i := 1; i <= x; i++ {
		now := i * i
		next := (i + 1) * (i + 1)

		if now <= x && next > x {
			return i
		}
	}

	return 0
}
func mySqrt(x int) int {
    left := 0
    right := x
    for left <= right {
        mid := left + (right-left)>>1
        current := mid * mid
        next := (mid+1) * (mid+1)
        if current <= x && next > x {
            return mid
        }else if current > x {
            right = mid - 1
        }else {
            left = mid + 1
        }
    }
    return 0
}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub