Leetcode---69. SQRT (x)

Source: Internet
Author: User

Title Link: Sqrt (x)

Implement int sqrt (int x).

Compute and return the square root of X.

The requirement for this problem is to implement the int sqrt (int x), which is the square root of the computed x.

Consider two points, that is, shillings L and R are 1 and x/2+1 (the square root of x must be less than or equal to x/2+1), then M equals (l+r)/2, and the size of m*m and X is constantly compared.

Due to m*m, it is possible to overflow, so you can use division instead of multiplication, or a long long type.

Complexity of Time: O (LOGN)

Space complexity: O (1)

1 class Solution{2  Public:3     int sqrt(int x) 4     {5         if(x == 0)6             return 0;7         8         int L = 1, R = x / 2 + 1;9          while(L <= R)Ten         { One             int m = (L + R) / 2; A              -             if(m <= x / m && m + 1 > x / (m + 1)) -                 return m; the                  -             if(m > x / m) -                 R = m - 1; -             Else if(m < x / m) +                 L = m + 1; -         } +         return L; A     } at };

Of course, this problem can also be used as a bitwise operation or Newton method.

Reprint please indicate source: Leetcode---69. SQRT (x)

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.