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

Sqrt(x)

时间:2017-06-10 20:29:57      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:style   blog   solution   sqrt   int   span   ==   logs   return   

方法:采用二分查找

class Solution {
public:
    int mySqrt(int x) {
        if(x == 0 || x == 1)
            return x;
            
        int lt = 0, rt = x;
        while(lt <= rt)
        {
            int mid = (lt + rt) / 2;
            if(x / mid == mid)
                return mid;
            if(x / mid < mid)
                rt = mid - 1;
            else
                lt = mid + 1;
        }
        
        return rt;
    }
};

 

Sqrt(x)

标签:style   blog   solution   sqrt   int   span   ==   logs   return   

原文地址:http://www.cnblogs.com/chengyuz/p/6979597.html

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