Square root of leetcode-069-x

Time:2022-1-5

Square root of X

Title Description: implement int sqrt (int x) function.

Calculates and returns the square root of X, where x is a nonnegative integer.

Since the return type is an integer, only the integer part of the result will be retained, and the decimal part will be rounded off.

See leetcode’s official website for an example.

Source: leetcode
Link: https://leetcode-cn.com/probl…
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Solution 1: dichotomy

First, set a minimum value min as 1 and a maximum value Max as 46340Math.sqrt(Integer.MAX_VALUE)And then mid is the intermediate value:

  • Ifmid*midIf it is equal to x, it returns directlymid
  • Ifmid*midIf it is less than x, set min to mid + 1 and make the next round of judgment again;
  • Ifmid*midIf it is greater than x, set Max to mid-1 and make the next round of judgment again;
  • The termination condition is that Max is not greater than min.

Finally, the mid is returned.

public class LeetCode_069 {
    public static int mySqrt(int x) {
        int min = 1, max = 46340, mid = 1;
        mid = (min + max) / 2;
        while (min < max) {
            int temp = mid * mid;
            if (temp == x) {
                return mid;
            } else if (temp < x) {
                min = mid + 1;
            } else {
                max = mid - 1;
            }
            mid = (min + max) / 2;
        }
        return mid;
    }

    public static void main(String[] args) {
        System.out.println(mySqrt(4));
    }
}

[daily message]Your efforts today are the foreshadowing of luck. Your efforts at present are the flowers of tomorrow.