leetcode : Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

只要返回int值,用二分查找,但是整型会溢出,更坑爹的是,当你发生溢出的时候提示的是超时。。。。。

所以用除法而不用乘法

AC代码:

class Solution {
public:
    int sqrt(int x) {
        if(x < 2)
            return x;
        if(x == 2)
            return 1;
        int start = 1, end = x, mid;
        while(start <= end){
            mid = start + (end - start) >> 1;  //防止start+end溢出
            if(mid == x / mid)
                return mid;
            else if(mid > x / mid)          //防止mid * mid溢出
                end = mid - 1;
            else if(mid < x / mid)
                start = mid + 1;
        }
        return end;
    }
};

 

posted on 2014-11-27 12:34  远近闻名的学渣  阅读(139)  评论(0)    收藏  举报

导航