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

lintcode-easy-Sqrt(x)

时间:2016-03-07 08:55:58      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

Implement int sqrt(int x).

Compute and return the square root of x.

sqrt(3) = 1

sqrt(4) = 2

sqrt(5) = 2

sqrt(10) = 3

mid*mid 以及 (mid + 1) * (mid + 1)都有可能溢出,所以要使用long类型。

class Solution {
    /**
     * @param x: An integer
     * @return: The sqrt of x
     */
    public int sqrt(int x) {
        // write your code here
        
        if(x <= 1)
            return x;
        
        long left = 1;
        long right = x / 2;
        
        while(left < right){
            long mid = left + (right - left) / 2;
            
            if((mid * mid) <= x && ((mid + 1) * (mid + 1)) > x)
                return (int)mid;
            else if(((mid + 1) * (mid + 1)) <= x)
                left = mid + 1;
            else 
                right = mid - 1;
        }
        
        return (int)left;
    }
}

 

lintcode-easy-Sqrt(x)

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5249293.html

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