[LintCode] 586 Sqrt(x) II 解题报告

Description
Implement double sqrt(double x) and x >= 0.

Compute and return the square root of x.

Notice
You do not care about the accuracy of the result, we will help you to output results.


Example
Given n = 2 return 1.41421356

5/2/2017

算法班

注意第10-12行,当x小于1时,mid只能无限接近x,而不会等于或者超过x。而在这个范围内sqrt(x) > x,所以需要把end设为1

(或者判断范围改变循环里面???)

 1 public class Solution {
 2     /**
 3      * @param x a double
 4      * @return the square root of x
 5      */
 6     public double sqrt(double x) {
 7         // Write your code here
 8         double start = 0;
 9         double end = x;
10         if (end < 1) {
11             end = 1;
12         }
13 
14         while (end - start > 1e-12) {
15             double mid = (start + end) / 2;
16             if (mid * mid < x) {
17                 start = mid;
18             } else {
19                 end = mid;
20             }
21         }
22         return start;
23     }
24 }

 

posted @ 2017-05-03 12:27  panini  阅读(1243)  评论(0编辑  收藏  举报