标签:
Implement int sqrt(int x)
.Compute and return the square root of x.
题意:算一个数的平方根。
好不容易想到用二分查找来解决改题,但是也破费了点力气,放到eclipse中调试来出来。注意点就是:取中值相乘,有可能会超过整数的最大范围,所以比较的时候就会出错。所以在定义的时候全部定义为long型。
第一版:
public int mySqrt(int x) { if (x == 0) return 0; long low = 1; long high = x; long tmp; long mid = 1; while (low <= high)//二分查找 { mid = (low + high) / 2; tmp = mid * mid; if (tmp == x) return (int)mid; else if (tmp > x) high = mid - 1; else if (tmp < x) low = mid + 1; } return (int)((mid*mid)>x?mid-1:mid); }
public int mySqrt(int x) { long low = 0; long high = x/2+1;//平方根的值按规律发现不会大于它的中值+1。这样每个查找就少了一次 long tmp; long mid = 1; while (low <= high) { mid = (low + high) / 2; tmp = mid * mid; if (tmp == x) return (int)mid; else if (tmp > x) high = mid - 1; else if (tmp < x) low = mid + 1; } return (int)high; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/fumier/article/details/47083605