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

Sqrt(x)

时间:2015-03-13 00:06:21      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

Implement int sqrt(int x).

Compute and return the square root of x.

思路:binary search ,柯西不等式 √ab<=(a+b)/2;

注意:overflow问题。新技巧:如果是乘法引起的overflow,可以试试改成除法。!!so clever!

class Solution {
public:
    /*overflow must be considered*/
    int sqrt(int x) {
        int a=1;
        int b=x;
        int mid=0;
        while(a<b){
            mid=(a+b)/2;
            if(mid>x/mid) b=mid-1;
            else a=mid+1;
        }
        
        if(a*a>x) return a-1;
        else return b;
        
    }
};

 

Sqrt(x)

标签:

原文地址:http://www.cnblogs.com/renrenbinbin/p/4333868.html

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