At first glance, this question is very simple. In fact, there are many problems to pay attention.
Note that the returned int value is an approximate value for the function interface. How can this problem be solved? Is it from 2? Until a value is close to x? Of course not. It must have timed out. Let's take a closer look. By the way, there is a binary method. From the maximum point, calculate the square value each time. If the result is greater than x, the upper bound is shortened; otherwise, the lower bound is increased.
The idea is correct. What is the biggest value below? You will not hesitate to say it is x. The square root of x must be smaller than x. Well, if x is INT_MAX, what type do you want to store this square result? In this way, it will take a while to converge each time. After all, INT_MAX is too large. Let's take a closer look. In fact, the maximum value is not x, but the square root of x, right, because we are looking for the square root.
There are two other questions. First, how can we determine that this value is close enough to x? Let's see if the difference between its square and x is less than a threshold value? I believe that this threshold value should not be a fixed value, but a change. After all, if the number is small, a small difference also indicates a great difference. Is there any more concise method? Of course, because int is returned, just calculate that the square of a is smaller than x, and the square of (a + 1) is larger than x, in addition, the result of the square of a can be used directly when the square of (a + 1) is obtained. Well, the second question is, What type is used to store the square of a and (a + 1? Int? It must have exceeded because the maximum value of a is sqrt (INT_MAX), and the square of (a + 1) must have exceeded int. You should use long.
The code is still very simple:
class Solution {public: int sqrt(int x) { if(x == 1) return 1; int MAX = 46340; int middle, start = 0, end = x; while(start<=end){ middle = min(MAX, start+(end-start)/2); long long tp1 = middle*middle; long long tp2 = tp1+2*middle+1; if(tp1<=x&&tp2>x) return middle; if(tp1>x) end = middle-1; else start = middle+1; } return 0; }};