力扣(LeetCode)试题69-x的平方根 C++代码

感想:在力扣练题,真的可以让你思维变得严谨,提交时再一次因为数据溢出翻车。。。

方法:首先使用的二分法,但是提交时系统的输入为2147395599,取中间值在平方时直接溢出报错。

经题解提醒,相当了迭代法,具体过程如下:

 

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class Solution 
 6 {
 7 public:
 8     int mySqrt(int x) 
 9     {
10         if (x == 0) return 0;
11         else
12         if (x == 1) return 1;
13         else
14         {
15             
16             int pre = (1/2 + (x / 1)/2);//将初始值设为1,并把结果作为pre,如果pre==1,则收敛于
17             //注意,不要写成 (1 + (x / 1)) / 2 这个形式,为啥?考虑一下
18             int cur = 0;
19             while (true)
20             {
21                 if (pre == 1)
22                     break;
23                 else
24                 {
25                     cur = (pre + (x / pre)) / 2;
26                     if (cur == pre || cur > pre)//有可能不收敛,会出现cur与pre来回切换,比如x=8时,所以有另一个条件
27                         break;
28                     else
29                         pre = cur;
30                 }
31             }
32             return pre;
33         }
34 
35 
36         //二分法
37         /*if (x == 0) return 0;
38         else
39         if (x == 1) return 1;
40         else
41         {
42 
43             int min = 0;
44             int max = x;
45             while (true)
46             {
47                 int mid = (min + max) / 2;
48                 if (mid*mid > x)
49                     max = mid;
50                 else
51                     min = mid;
52 
53                 if (max - min == 1)
54                 {
55                     return min;
56                     break;
57                 }
58             }
59         }*/
60     }
61 };
62 
63 int main()
64 {
65     int x = 2147483647;
66     int result;
67     Solution sol;
68     result = sol.mySqrt(x);
69     cout << result << endl;
70 
71     int u;
72     cin >> u;
73     return 0;
74 }

 

 

 

 

 

 

posted @ 2020-07-11 20:40  ZyLin-ux  阅读(335)  评论(0编辑  收藏  举报