sudopower

LC: 69: Sqrt(x)

lc_69

Link to problem

Solution 2 – Binary search

func mySqrt(x int) int {
    // keep finding square root for nos less than x
    // optimize using binary search
    // return the last checked no as result
    if x==1{
        return 1
    }
    var start,end,mid int
    end=x/2    
    for start<=end{                
        
        if mid*mid==x{
            break
        }

        if mid*mid<x{
            start=mid+1
        } else {
            end=mid-1
        }                
        mid=(start+end)/2
    }
    return mid
}

Solution 2 – Brute Force

func mySqrt(x int) int {
    // brute force
    if x<2{
        return x
    }
    if x==2{
        return 1
    }
    var i int
    for i = range x{
        if (i*i)>x{
            break
        }
    }
    return i-1
}

Leave a Reply

Your email address will not be published. Required fields are marked *