`
hcx2013
  • 浏览: 83067 次
社区版块
存档分类
最新评论

Sqrt(x)

 
阅读更多

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 i = 0;
        long j = x / 2 + 1;
        while (i <= j) {
            long mid = (i + j) / 2;
            long sq = mid * mid;
            if (sq == x) {
            	return (int) mid;
            } else if (sq < x) {
            	i = mid + 1;
            } else {
            	j = mid - 1;
            }
        }
        return (int)j;
    }
}

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics