问题:手写代码实现sqrt函数,即求一个整数的平方根
分析:二分查找思想
1 #include <iostream>
2
3 using namespace std;
4
5 int sqrt(int x)
6 {
7 long left = 0;
8
9 if(x == 1)
10 return 1;
11 long right = x;
12
13 long mid = left + (right - left)/2;
14 while(left + 1 < right)
15 {
16 if(x > mid * mid)
17 {
18 left = mid;
19 }
20 else if(x < mid * mid)
21 {
22 right = mid;
23 }
24 else
25 {
26 return mid;
27 }
28 mid = left + (right - left)/2;
29 }
30 return left;
31 }
32
33 int main()
34 {
35 cout << "144 的平方根为:" << sqrt(144) << endl;
36 return 0;
37 }