9. Sqrt(x) - Jake blog - Java coding practice log (2017)" /> 9. Sqrt(x) - Jake blog - Java coding practice log (2017)" />

69. Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

Approach:

This problem isn't difficult; binary search 1-x will suffice. There are a few details to be aware of.

  1. To find the median value, use start + (end - start) / 2, not (start + end) / 2, to avoid the sum of start + end exceeding the range.
  2. Don't use `mid*mid == x` either; use `mid = x/mid` instead, for the same reason as above.
public class Solution { public int mySqrt(int x) { int start=1; int end = x; if(x<2) return x; while(start x / (mid + 1)){ return mid; } if(mid > x / mid){ end =mid; } else{ start =mid+1; } } return -1; } }

This websiteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:"69. Sqrt(x)"

164
0 0 164

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top