码迷,mamicode.com
首页 > 其他好文 > 详细

x的平方根

时间:2015-09-05 11:11:19      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

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越界

x的平方根

标签:

原文地址:http://www.cnblogs.com/smallby/p/4782838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!