力扣算法题—069x的平方根

实现 int sqrt(int x) 函数。

计算并返回 x 的平方根,其中 是非负整数。

由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

示例 1:

输入: 4
输出: 2

示例 2:

输入: 8
输出: 2
说明: 8 的平方根是 2.82842..., 
     由于返回类型是整数,小数部分将被舍去。

 1 #include "_000库函数.h"
 2 
 3 //最简单想法,耗时长
 4 class Solution {
 5 public:
 6     int mySqrt(int x) {
 7         if (x <= 1)return x;
 8         double n = 0;//防止int溢出
 9         while (++n) {
10             if (n*n > x) {
11                 --n;
12                 return (int)n;
13             }
14             else if (n*n == x)
15                 return (int)n;
16         }
17         return 0;//力扣非得要在这里加一个return,无语了
18     }
19 };
20 
21 //用对折法
22 //因为x为int,最大为65536的平方
23 //贼鸡儿快,内存很少
24 class Solution {
25 public:
26     int mySqrt(int x) {
27         if (x <= 1)return x;
28         double min = 1, max = 65536, mid = (int)((min + max)/2);//防止int溢出
29         while (min < max&&mid*mid != x) {
30             if (mid*mid < x)min = mid + 1;
31             else max = mid - 1;
32             mid = (int)((min + max)/2);
33         }
34         if (mid*mid > x)--mid;
35         return (int)mid;
36     }
37 };
38 
39 
40 //同样折半,更简洁
41 class Solution {
42 public:
43     int mySqrt(int x) {
44         if (x <= 1) return x;
45         int left = 0, right = x;
46         while (left < right) {
47             int mid = left + (right - left) / 2;
48             if (x / mid >= mid) left = mid + 1;
49             else right = mid;
50         }
51         return right - 1;
52     }
53 };
54 
55 //更牛逼的方法
56 //用牛顿迭代法,记得高数中好像讲到过这个方法,是用逼近法求方程根的神器,
57 //因为要求x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,可以求出递推式如下:
58 //
59 //xi + 1 = xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n / xi) / 2
60 
61 class Solution {
62 public:
63     int mySqrt(int x) {
64         long res = x;
65         while (res * res > x) {
66             res = (res + x / res) / 2;
67         }
68         return res;
69     }
70 };
71 void T069() {
72     Solution s;
73     cout << "2:    " << s.mySqrt(2) << endl;
74     cout << "8:    " << s.mySqrt(8) << endl;
75     cout << "0:    " << s.mySqrt(0) << endl;
76     cout << "9:    " << s.mySqrt(9)<<endl;
77 }

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/10696512.html