The eighth question of "Starting from 0 to make LeetCode"
tag: binary search
Difficulty: easy
Implement the int sqrt(int x) function.
Calculate and return the square root of x, where x is a non-negative integer.
Since the return type is an integer, only the integer part of the result is retained, and the decimal part will be discarded.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Description: The square root of 8 is 2.82842..., since the return type is an integer, the decimal part will be truncated.
Source: LeetCode
Link: https://leetcode-cn.com/problems/sqrtx
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Note: There is also a faster algorithm for this problem- Newton's iteration method , which will be learnt later.
class Solution {
public:
int mySqrt(int a) {
if (a == 0) return a;
int l = 1, r = a, mid, sqrt;
while (l <= r) {
mid = l + (r - l) / 2;
sqrt = a / mid;
if (sqrt == mid) {
return mid;
} else if (mid > sqrt) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return r;
}
};