[Leetcode] SQRT (X)

Source: Internet
Author: User
Tags square root
SQRT (X)

Implementint sqrt(int x).

Compute and return the square rootX.

Note ]:

1. Int type may overflow, so multiplication is not allowed. Try to use division.

2. The vast majority of numbers are not open-ended. How can we get close results?

Algorithm ideas:

Train of Thought 1: sequential traversal certainly does not need to be tested. Binary Search is more reliable. The bipartite method is very common in numerical computation and requires proficiency.

The Code is as follows:

Public class solution {public int SQRT (int x) {If (x <= 1) return x = 0? 0: X; int L = 1, R = X/2 + 1; while (L <= r) {int mid = (L + r)/2; if (mid <= x/Mid & (Mid + 1)> X/(Mid + 1) {return mid; // here is a clever use} else if (mid> X/Mid) {r = mid-1;} else {L = Mid + 1 ;}} return 0 ;}}

Idea 2: Newton Iteration Method; relatively tall, please stamp the detailed analysis process here.

The Code is as follows:

 1 public int sqrt(int x) { 2     if (x == 0) return 0; 3     double lastY = 0; 4     double y = 1; 5     while (y != lastY) 6     { 7         lastY = y; 8         y = (y + x / y) / 2; 9     }10     return (int)(y);11 }

This question is very good.

 

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.