LeetCode 69 questions: x square root of (simple)

LeetCode 69 questions: x square root of (simple)

  • Topic: Implementing int sqrt (int x) function. Computes and returns the square root of x, where x is a non-negative integer. Since the return type is an integer, the integer part of the result to retain only the fractional part is rounded down.
  • A thought: uh. . . Doing a bit too much 2333
class Solution {
    public int mySqrt(int x) {
        int ans = (int)Math.sqrt(x);
        return ans;
    }
}

Here Insert Picture Description

  • Thinking two: just no place at the beginning while the value of ans limits, but overflowed. ans it can be up to 46340, so it has been restricted.
class Solution {
    public int mySqrt(int x) {
        int ans=0;
        while(ans*ans<=x && ans<=46340){
            ans++;
        }
        return ans-1;
    }
}

Here Insert Picture Description

  • Thinking three: the dichotomy.
class Solution {
  public int mySqrt(int x) {
    if (x < 2) return x;

    long num;
    int pivot, left = 2, right = x / 2;
    while (left <= right) {
      pivot = left + (right - left) / 2;
      num = (long)pivot * pivot;
      if (num > x) right = pivot - 1;
      else if (num < x) left = pivot + 1;
      else return pivot;
    }

    return right;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/sqrtx/solution/x-de-ping-fang-gen-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Here Insert Picture Description

  • Ideas Four: I did not expect this question so many ideas. You can use recursion.
    Here Insert Picture Description
class Solution {
  public int mySqrt(int x) {
    if (x < 2) return x;

    int left = mySqrt(x >> 2) << 1;
    int right = left + 1;
    return (long)right * right > x ? left : right;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/sqrtx/solution/x-de-ping-fang-gen-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Here Insert Picture Description

  • Ideas Five: Newton's method.
class Solution {
  public int mySqrt(int x) {
    if (x < 2) return x;

    double x0 = x;
    double x1 = (x0 + x / x0) / 2.0;
    while (Math.abs(x0 - x1) >= 1) {
      x0 = x1;
      x1 = (x0 + x / x0) / 2.0;
    }

    return (int)x1;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/sqrtx/solution/x-de-ping-fang-gen-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Here Insert Picture Description

Published 79 original articles · won praise 7 · views 1370

Guess you like

Origin blog.csdn.net/new_whiter/article/details/104392467