Sqrt(x)

时间:2015-05-30 02:14:16   收藏:0   阅读:371

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;
        		}
        	}
        }
    }
}

?

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

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!