Algorithm leetcode|69. The square root of x (rust strikes hard)



69. Square root of x:

Given a non-negative integer x, compute and return xthe arithmetic square root of .

Since the return type is an integer, only the integer part of the result is kept , and the decimal part will be discarded .

NOTE : Any built-in exponential functions and operators such as pow(x, 0.5)or are not allowed x ** 0.5.

Example 1:

输入:
	
	x = 4
	
输出:
	
	2

Example 2:

输入:
	
	x = 8
	
输出:
	
	2
	
解释:
	
	8 的算术平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。

hint:

  • 0 <= x <= 231 - 1

analyze:

  • Facing this algorithm problem, the second leader fell into deep thought again.
  • The square root is required, but the built-in exponential function is not allowed, which is deliberately difficult for me.
  • Brute force cracking, anyway, as long as integers, from 1 to x, try one by one, you can find the closest solution, it is very simple, but it is too simple, there must be a better way.
  • The answer only needs to be an integer. Find the optimal value from the linear continuous value. I think that I can use the dichotomy method and keep trying. The efficiency of dichotomy is very high, and the amount of data can be reduced by half every time, which is already satisfactory.
  • There is a better way. The answer needs to be an approximate integer, so you can also use the Newton iterative method , which is very suitable for finding an approximate solution efficiently. It is said that the efficiency is higher than the binary score.
  • I feel that mathematics is still very powerful. Many things can be solved efficiently with mathematical methods. Although computers are already very fast, many times it can be solved much faster with mathematical methods. I really want to learn mathematics well.
  • The solutions to the following problems all use the Newton iterative method to find approximate solutions, so there needs to be a degree, a point to stop continuing. It is generally believed that when the difference between the two consecutively obtained solutions is very small, it is time to stop.

answer:

rust:

impl Solution {
    
    
    pub fn my_sqrt(x: i32) -> i32 {
    
    
        if x == 0 {
    
    
            return 0;
        }

        let (c, mut x0) = (x as f64, x as f64);
        loop {
    
    
            let xi = 0.5 * (x0 + c / x0);
            if (x0 - xi).abs() < 1e-7 {
    
    
                break;
            }
            x0 = xi;
        }

        return x0 as i32;
    }
}

go:

func mySqrt(x int) int {
    
    
    if x == 0 {
    
    
		return 0
	}

	c, x0 := float64(x), float64(x)
	for {
    
    
		xi := 0.5 * (x0 + c/x0)
		if math.Abs(x0-xi) < 1e-7 {
    
    
			break
		}
		x0 = xi
	}

	return int(x0)
}

c++:

class Solution {
    
    
public:
    int mySqrt(int x) {
    
    
        if (x == 0) {
    
    
            return 0;
        }

        double c = x, x0 = x;
        while (true) {
    
    
            double xi = 0.5 * (x0 + c / x0);
            if (fabs(x0 - xi) < 1e-7) {
    
    
                break;
            }
            x0 = xi;
        }

        return int(x0);
    }
};

python:

class Solution:
    def mySqrt(self, x: int) -> int:
        if x == 0:
            return 0

        c, x0 = float(x), float(x)
        while True:
            xi = 0.5 * (x0 + c / x0)
            if abs(x0 - xi) < 1e-7:
                break
            x0 = xi

        return int(x0)


java:

class Solution {
    
    
    public int mySqrt(int x) {
    
    
        if (x == 0) {
    
    
            return 0;
        }

        double c = x, x0 = x;
        while (true) {
    
    
            double xi = 0.5 * (x0 + c / x0);
            if (Math.abs(x0 - xi) < 1e-7) {
    
    
                break;
            }
            x0 = xi;
        }

        return (int) x0;
    }
}

Thank you very much for reading this article~
Welcome to [Like][Favorite][Comment] Go three times in a row~It’s
not difficult to give up, but it must be cool~
I hope we all can improve a little every day~
This article is written by the white hat of the second master: https://le-yi.blog.csdn.net/Blog original~


Guess you like

Origin blog.csdn.net/leyi520/article/details/132203921