
Problem
Solution
Submissions
Square Root Function
Certification: Basic Level
Accuracy: 100%
Submissions: 1
Points: 5
Write a Java program to compute and return the square root of a non-negative integer x, rounded down to the nearest integer (the floor value). You are not allowed to use any built-in square root function or operator.
Example 1
- Input: x = 4
- Output: 2
- Explanation:
- Step 1: Use binary search approach to find the square root of the integer.
- Step 2: The search range is initially from 1 to x.
- Step 3: For x = 4, the middle value is 2.
- Step 4: Since 2 * 2 = 4, which equals x, return 2 as the answer.
Example 2
- Input: x = 8
- Output: 2
- Explanation:
- Step 1: Use binary search approach to find the square root of the integer.
- Step 2: The search range is initially from 1 to 8.
- Step 3: For x = 8, we need to find the largest integer whose square is less than or equal to 8.
- Step 4: Check 2: 2 * 2 = 4, which is less than 8.
- Step 5: Check 3: 3 * 3 = 9, which is greater than 8.
- Step 6: Return 2 as the floor value of the square root of 8.
Constraints
- 0 ≤ x ≤ 2^31 - 1
- You cannot use any built-in library function like Math.sqrt()
- Time Complexity: O(log x)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use binary search to find the square root
- Start with a search range from 1 to x
- For each mid value, check if mid * mid is less than or equal to x
- Be careful with integer overflow when calculating mid * mid
- Return the largest integer whose square is less than or equal to x