Here is the requirement of a problem: Implement int sqrt(int x). Compute and return the truncated square root of x. x is guaranteed to be a non- negative integer. Example 1: Input: 4 Output: 2 Example...


Please answer the question in the screenshot. Please give reasoning.


Here is the requirement of a problem:<br>Implement int sqrt(int x). Compute and return the truncated square root of x. x is guaranteed to be a non-<br>negative integer.<br>Example 1:<br>Input: 4<br>Output: 2<br>Example 2:<br>Input: 8<br>Output: 2<br>Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part<br>will be truncated.<br>Here is the solution of one programmer:<br>class Solution {<br>public int mysqrt(int x) {<br>if (x == 0) return 0;<br>int left = 1, right = x, ans=right;<br>while (left <= right) {<br>int mid = left + (right - left) / 2;<br>if (mid >= x / mid) {<br>right = mid - 1;<br>ans = mid;<br>} else {<br>left = mid + 1;<br>}<br>}<br>return ans;<br>}<br>}<br>Do you think the above solution is correct? If not, why?<br>

Extracted text: Here is the requirement of a problem: Implement int sqrt(int x). Compute and return the truncated square root of x. x is guaranteed to be a non- negative integer. Example 1: Input: 4 Output: 2 Example 2: Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated. Here is the solution of one programmer: class Solution { public int mysqrt(int x) { if (x == 0) return 0; int left = 1, right = x, ans=right; while (left <= right)="" {="" int="" mid="left" +="" (right="" -="" left)="" 2;="" if="" (mid="">= x / mid) { right = mid - 1; ans = mid; } else { left = mid + 1; } } return ans; } } Do you think the above solution is correct? If not, why?

Jun 06, 2022
SOLUTION.PDF

Get Answer To This Question

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here