x的平方根

class Solution {
public:
    /**
     * @param x: An integer
     * @return: The sqrt of x
     */
     int getResult(long start, long end, long target){
        long temp;
        while(start <= end){
            temp = (start + end) / 2;
            if(start * start > target)
                return start -1;
            if(end * end < target)
                return end;
            if(temp * temp == target)
                return temp;
            else if(temp * temp > target)
                end = temp -1;
            else if(temp * temp < target)
                start = temp + 1;
        }
    }
    int sqrt(int x) {
        // write your code here
        if(x == 0)
            return 0;
        else if(x <= 3)
            return 1;
        else if(x > 3)
            return getResult(3, x/2+1 ,x);
    }
};

ps:注意int越界

posted @ 2015-09-05 10:20  影翕  阅读(176)  评论(0编辑  收藏  举报