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
classSolution{publicintmySqrt(int x){int ans =(int)Math.sqrt(x);return ans;}}
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.
classSolution{publicintmySqrt(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;elseif(num < x) left = pivot +1;elsereturn pivot;}return right;}}
作者:LeetCode
链接:https://leetcode-cn.com/problems/sqrtx/solution/x-de-ping-fang-gen-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Ideas Four: I did not expect this question so many ideas. You can use recursion.
classSolution{publicintmySqrt(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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。