69. Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
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: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
Solution
處理數相關的問題,盡量透過減法、除法、shift位元的方式進行計算,減少溢位出錯
此題用binary Search求解。 narrow down可用的range直到left == right為止。
此時left/right值可能跟所求一步之遙,要看上次binary search的運作是判斷到left導致left增加 or right導致right減少。 所以還要額外判斷哪個才是對的。
public int mySqrt(int x) {
if (x == 0) return 0;
int right = x, left = 1;
while(right > left){
int mid = left + (right - left)/2;
if(mid == x/mid) return mid;
else if (mid > x/mid)
{
right = mid - 1;
}else{
left = mid+1;
}
}
return (left > x/left) ? left-1 : left;
}
Last updated
Was this helpful?