SQRT (x)

Source: Internet
Author: User
Tags square root

Implement int sqrt(int x) .

Compute and return the square root of X.

Has you met this question in a real interview?Yes Example

sqrt (3) = 1

sqrt (4) = 2

sqrt (5) = 2

sqrt (10) = 3

1 classSolution {2     /**3 * @param x:an integer4 * @return: The sqrt of x5      */6      Public intsqrtintx) {7         LongStart =0;8         LongEnd =x;9 Ten          while(Start <=end) { One             LongMID = start + (End-start)/2; A             if(Mid * mid = =x) { -                 return(int) mid; -}Else if(Mid * Mid <x) { theStart = mid +1; -}Else { -End = Mid-1; -             } +         } -         return(int) (Start-1); We are looking for lower end. +     } A}

Or we can do it another.

1 classSolution {2     /**3 * @param x:an integer4 * @return: The sqrt of x5      */6      Public intsqrtintx) {7         LongStart =0;8         LongEnd =x;9 Ten          while(Start <=end) { One             LongMID = start + (End-start)/2; A             if(Mid * mid = =x) { -                 return(int) mid; -}Else if(Mid * Mid < x && (mid +1) * (Mid +1) >x) { the                 return(int) mid; -}Else if(Mid * Mid <x) { -Start = mid +1; -}Else { +End = Mid-1; -             } +         } A         return-1; at     } -}

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.