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

Leetcode Sqrt(x)

时间:2015-10-22 01:38:48      阅读:262      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!