首页 > 其他 > 详细

Leetcode Sqrt(x)

时间:2015-10-22 01:38:13      阅读:186      评论:0      收藏:0      [点我收藏+]

Implement int sqrt(int x).

Compute and return the square root of x.


解题思路:

对于一个非负数n,它的平方根不会大于(n/2+1)。在[0, n/2+1]这个范围内可以进行二分搜索(binary search),求出n的平方根。

注:在中间过程计算平方的时候可能出现溢出,所以用long.


Java code:

public class Solution {
    public int mySqrt(int x) {
        long i = 0;
        long j = x / 2 + 1;
        while(j >= i){
            long mid = (i + j) / 2;
            long sqr = mid * mid;
            if(sqr == x) {
                return (int)mid;
            }else if(sqr < x){
                i = mid + 1;
            }else {
                j = mid - 1;
            }
        }
        return (int)j;
    }
}

Reference:

1. http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html

 

Leetcode Sqrt(x)

原文:http://www.cnblogs.com/anne-vista/p/4899698.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!