[Leetcode] [Java] SQRT (x)

Source: Internet
Author: User
Tags square root

Title:

Implement int sqrt(int x) .

Compute and return the square root of X.

Test Instructions:

Implement the root function.


Algorithm Analysis:


The problem of this mathematical operation, just start the first time when the brush to tell the truth I was cheating AC. After a lot of senior blog said this topic interview is very common, suggest or think about it well.


Reference is made to HTTP://PISXW.COM/ALGORITHM/SQRT (x). html

The problem uses another method that is often used in numerical values: the dichotomy. The basic idea is similar to binary search, the requirement is to know the scope of the results, to set the left and right boundaries, and then every time you cut off the half of the conditions, until the left and right to meet.

The more typical numerical processing problems are Divide two integers,Pow (X,n), and so on, in fact, the method is similar, generally is the dichotomy or 2-based processing method.


AC Code:
public class Solution {public    int sqrt (int x) {        ////know the scope of the result, you can use the dichotomy        if (x<0)  return-1;        if (x==0) return 0;        int left=1;        int right=x/2+1;        while (Left<=right)        {            int m= (left+right)/2;            if (m<=x/m && (m+1) >x/(m+1))                return m;            if (m>x/m)                right=m-1;            else                left=m+1;        }        return 0;}    }


Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode] [Java] SQRT (x)

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.