LeetCode69 如果求一个数的平方根?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/si444555666777/article/details/82499315

方法1:使用二分查找

	public static double sqrt(double t) {
		//初始化上界和下届
		double low=0;
		double high=t;
		double mid=low+(high-low)/2;
		//给定精度
		while(high-low>1e-7) {
			if(mid*mid>t)
				high=mid;
			else if(mid*mid<t)
				low=mid;
			else if(Math.abs(mid*mid-t)<1e-7) {
				return mid;
			}
			mid=low+(high-low)/2;			
		}
		return mid;	
	}

方法2:使用牛顿迭代法

牛顿迭代法原理:https://blog.csdn.net/wxn704414736/article/details/78652326

public static int mySqrt(int x) 
	{
	        if (x <= 1) return x;
	        double x1 = 0, x2 = 1;
	        while (Math.abs(x1 - x2) > 0.000001) 
	        {
	            x1 = x2;
	            x2 = x1 / 2 + (double)x / (2 * x1);
	        }
	        return (int)x1;
	}

猜你喜欢

转载自blog.csdn.net/si444555666777/article/details/82499315
今日推荐