File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -25,6 +25,44 @@ public int mySqrt(int x) {
2525}
2626
2727
28+ /*
29+ 牛顿迭代:从大到小逼近
30+ 1、求根号x的近似值res,先令 res 为 x,即从一个大数开始迭代逼近,不断令 res 等于 (res+x/res)/2,由于是向下取整,当 res * res <= x时,此时res为最终结果值
31+ 2、res要用long类型,计算过程如果为整型会溢出,最后结果再强转为整型即可
32+
33+ x = 5
34+ res = 5 → 3 → 2
35+ */
36+ class Solution {
37+ public int mySqrt (int x ) {
38+ long res = x ;
39+ while (res * res > x ) {
40+ res = (res + x / res ) / 2 ;
41+ }
42+ return (int ) res ;
43+ }
44+ }
45+
46+
47+ /*
48+ 暴力:从小到大逼近
49+ 1、从1开始,平方值小于等于x,则继续查找,直到第一个平方值大于x结束循环,返回前一个值
50+ 2、平方值可能会溢出,要转为long类型
51+ */
52+ class Solution {
53+ public int mySqrt (int x ) {
54+ long res = 1 ;
55+ while (res * res <= x ) {
56+ res ++;
57+ }
58+ return (int ) res - 1 ;
59+ }
60+ }
61+
62+
63+ /*
64+ 库函数
65+ */
2866class Solution {
2967 public int mySqrt (int x ) {
3068 return (int ) Math .pow (x , 0.5 );
You can’t perform that action at this time.
0 commit comments