Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Example 1:
Input: x = 4
Output: 2
Example 2:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
x is a non-negative integer. There are no specific constraints, but typically for such problems, the value of x can be large, up to (2^{31} - 1) (the maximum value for a 32-bit signed integer).Math.sqrt()?
Math.sqrt(), as it demonstrates problem-solving skills and understanding of algorithms.x = 0 or x = 1?
0 is 0, and the square root of 1 is 1.We can solve this problem using the Binary Search algorithm:
left = 0 and right = x.left <= right, calculate the mid-point, mid = left + (right - left) / 2.mid * mid equals x, return mid.mid * mid is less than x, move left to mid + 1.mid * mid is greater than x, move right to mid - 1.right will be the integer part of the square root.public class Solution {
public int mySqrt(int x) {
if (x < 2) {
return x;
}
int left = 0;
int right = x;
int result = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid <= x / mid) {
result = mid; // mid is a potential answer
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
}
O(log x), because we are using binary search which divides the range in half for each iteration.O(1), as we are using a constant amount of extra space.This solution efficiently finds the integer part of the square root using binary search without relying on built-in functions, making it suitable for large input values.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?