卖萌的弱渣

I am stupid, I am hungry.

Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

Solution

  • Java:
(Sqrt.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    public int mySqrt(int x) {
        int l = 0;
        int r = Integer.MAX_VALUE;
        if(x==0)
            return 0;
        while (l<=r){
            int mid = l+(r-l)/2;
            if (mid > x/mid)
                r = mid-1;
            else{
                if (mid+1 >x/(mid+1))
                    return mid;
                l = mid+1;
            }

        }
        return l-1;
    }
}
  • 二分查找[0,x]直到找到
(Sqrtx.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        l = 0
        r = x

        if x == 0 or x == 1:
            return x
        while l <= r:
            m = (l+r)/2
            if m*m == x:
                return m
            elif m*m < x:
                l = m+1
            else:
                r = m-1
        return l-1