zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    [转载]网站运营粮草要先行
    微信公众平台开发(一) 配置接口
    UI框架说明
    布局
    DataGrid表格控件
    Dialog控件
    mysql出现 too many connections
    JVM调优案例
    ArrayBlockingQueue源码阅读
    jdk命令行工具
  • 原文地址:https://www.cnblogs.com/panini/p/6801314.html
Copyright © 2011-2022 走看看