Leetcode 69. SQRT (x)

Source: Internet
Author: User

SQRT (x)Total accepted:99997 Total submissions:388728 difficulty:medium

Implement int sqrt(int x) .

Compute and return the square root of X.

Idea: You can use the SQRT function directly. But in fact, this is a two-point search.

Code:
The simplest method:

1 class Solution {2public:3     int mysqrt (int x) {//15792052744         int half= ( int ) sqrt (x); 5         return half; 6     }7 };

Two-point search:

1 classSolution {2  Public:3     intMYSQRT (intx) {//15792052744         if(x<=1){5             returnx;6         }7         intleft=1, Right=x,mid;//left closed right open8          while(left<Right ) {9mid=left+ (Right-left)/2;//Direct use (high + low)/2 may cause overflowTen             if(x/mid>=mid) { OneLeft=mid+1; A             } -             Else{ -right=mid; the             } -         } -         returnleft-1; -     } +};

Leetcode 69. 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.