Jan 19-sqrt (x); Math; Binary Search;

Source: Internet
Author: User

We should keep in mind so never let the integer value overranged or overstacked.

Here are the trick, instead of comparing the square of a interger with the target value, we can compare the integer value I With the quotient x/i;

if (i > x/i) high = i-1; if (I < x/i) low = i +1, the condition of the and is loop are low < high. Thus when the loop is ends, low = high. There is and results, one is the low point to the integer which was the sqrt (x), the other is low = sqrt (x) +1. We need to check the "cases" in the end.

Code:

public class Solution {public    int mysqrt (int x) {        if (x<0) return-1;        if (x = = 0) return 0;        if (x = = 1) return 1;        int low = 1, high = x;        while (Low < high) {            int mid = low+ (high-low)/2;            int quotient = X/mid;            if (quotient = = mid) return mid;            else if (Mid > Quotient) {high                = mid-1;            }            else{Low                = mid + 1;            }        }        int quotient = X/low;        if (Low > Quotient) return low-1;        return low;    }}

  

Newton ' s method to get square root:

Code:

 Public int mysqrt (int  x) {    ifreturn 0;     long i = x;      while (i > x/ i)           = (i + x/i)/2;                 return (int) i;}

Jan 19-sqrt (x); Math; Binary Search;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.