首页 > 其他 > 详细

Sqrt(x)

时间:2015-05-30 02:14:16      阅读:371      评论:0      收藏:0      [点我收藏+]

Implement intsqrt(int x).

Compute and return the square root of?x.

?

Example

sqrt(3) = 1

sqrt(4) = 2

sqrt(5) = 2

sqrt(10) = 3

?

class Solution {
    /**
     * @param x: An integer
     * @return: The sqrt of x
     */
    public int sqrt(int x) {
        if (x == 1) {
        	return 1;
        }
        long t = x/2;
        long a = t;
        while (true) {
        	if (t * t > x) {
        		a = t;
        		t = t/2;
        	} else {
        		if ((t+1)*(t+1) > x) {
        			return (int) t;
        		} else {
        			t = (t+a)/2;
        		}
        	}
        }
    }
}

?

Sqrt(x)

原文:http://hcx2013.iteye.com/blog/2215276

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