题目描述:
不用sqrt(x)库函数,实现求平方根。
解题思路:
采用二分法
假定要求数num的平方根,那么首先取1~num之间的中点mid。
若 mid * mid > num,那么 根在 1~mid-1之间;
若 mid * mid < num,那么根在 mid+1~num 之间;
若 mid * mid == num,直接输出 mid;
由于整数int求平方根是向下取整,所以,若mid * mid < x情况下,根可能是mid. 依据上面假设根在mid+1~num之间,那么mid+1~num之间的所有跟都大于num。所以在退出的时候要处理一下。
<span style="font-size:18px;">if (min*min > num) return min - 1; else return min;</span>
参考代码:
<span style="font-size:18px;">class Solution{ public: int getSqrt(int num) { if(num <= 0) return 0; int min = 0; int max = num; int mid = (min + max) / 2; int mark = 0.001; while (min <= max) { if (mid*mid == num) return mid; else if (mid*mid < num) min = mid+1; else max = mid-1; mid = (min + max) / 2; } if (min * min > num) return min - 1; else return min; } };</span>
代码2:考虑精度估计个数约等于num的平方根,精度自定义,同样使用二分法。
float getSqrt(int num, float epsilon) { if(num <=0) return 0; float low, high, maymid; low = 0; high = max(1, num); maymid = (low + high) / 2.0; while (abs(maymid*maymid - num)>epsilon) { if (maymid * maymid == num) return maymid; if (maymid*maymid<num) low = maymid; else high = maymid; maymid = (low + high) / 2.0; } return maymid; }
参考资料:
http://blog.csdn.net/tosslee/article/details/6998448
http://blog.csdn.net/u012162613/article/details/41361655
时间: 2024-11-09 01:45:09