[Leetcode] SQRT (X)

Source: Internet
Author: User

ImplementInt SQRT (int x).

Compute and return the square rootX.

Https://oj.leetcode.com/problems/sqrtx/

 

Idea 1: the square root of a number must be 0 ~ X/2 + 1, so binary search in this range.

Note:

    • Long is used in the intermediate result; otherwise, mid * mid overflows.
    • Returns the floor value of the square root if no result is found.

Idea 2: Newton Iteration Method.

 

 Public   Class  Solution {  Public   Int SQRT ( Int X ){  If (X <0 )  Return -1 ;  Long Right = X/2 + 1 ;  Long Left = 0 ;  Long  Mid;  While (Left <= Right) {mid = (Left + right)/2;  If (X <mid * Mid) Right = Mid-1 ;  Else   If (X> mid * Mid) left = Mid + 1 ;  Else                  Return ( Int  ) Mid ;}  Return ( Int ) Right ;}  Public   Static   Void  Main (string [] ARGs) {system. Out. println (  New Solution (). SQRT (0 ); System. Out. println (  New Solution (). SQRT (1 ); System. Out. println (  New Solution (). SQRT (2 ); System. Out. println (  New Solution (). SQRT (3); System. Out. println (  New Solution (). SQRT (4 ); System. Out. println (  New Solution (). SQRT (2147483647 ));}} 
View code

 

Refer:

Http://blog.csdn.net/linhuanmars/article/details/20089131

Http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html

 

 

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.