zoukankan      html  css  js  c++  java
  • 69. Sqrt(x)

    题目:

    Implement int sqrt(int x).

    Compute and return the square root of x.

    链接:   http://leetcode.com/problems/sqrtx/

    2/14/2017, Java,不是自己想的。。。

    二分法,需要进行第3行的判断。最后返回hi的原因是从while loop挑出来的时候lo是比hi大的,实际上我们应该选小的那个值,就是hi

     1 public class Solution {
     2     public int mySqrt(int x) {
     3         if (x <= 1) return x;
     4 
     5         int lo = 0, hi = x;
     6         int mid;
     7         
     8         while( lo <= hi) {
     9             mid = lo + (hi - lo) / 2;
    10             if (mid < x / mid) {
    11                 lo = mid + 1;
    12             } else if (mid > x / mid) {
    13                 hi = mid - 1;
    14             } else {
    15                 return mid;
    16             }
    17         }
    18         return hi;
    19     }
    20 }

    牛顿法,肯定也不是自己想的。

    还是注意input = 1的情况

     1 public class Solution {
     2     public int mySqrt(int x) {
     3         if (x <= 1) return x;
     4         
     5         double lastY = x / 2;
     6         double Y = (lastY + x / lastY) / 2;
     7         
     8         while (Y != lastY) {
     9             lastY = Y;
    10             Y = (lastY + x / lastY) / 2;
    11         }
    12         return (int)Y;
    13     }
    14 }

    4/27/2017

    算法班,套用公式,不过不如一刷第一种方法好。

     1 class Solution {
     2     /**
     3      * @param x: An integer
     4      * @return: The sqrt of x
     5      */
     6     public int sqrt(int x) {
     7         // write your code here
     8         if (x <= 0) return 0;
     9         if (x == 1) return 1;
    10         
    11         int start = 1, end = x;
    12         while (start + 1 < end) {
    13             int mid = start + (end - start) / 2;
    14             if (x / mid == mid) {
    15                 return mid;
    16             } else if (x / mid > mid) {
    17                 start = mid;
    18             } else {
    19                 end = mid;
    20             }
    21         }
    22         if (x / start >= start) {
    23             return start;
    24         } else {
    25             return end;
    26         }
    27     }
    28 }
  • 相关阅读:
    前端面试攻略1------算法部分
    MongoDB学习
    MongoDB作为Windows服务来安装 错误1053:服务没有及时响应启动或控制请求
    Vue 入门之 Vuex 实战
    Vue 路由详解
    vue入门全局配置
    VSCode配合ESLint自动修复格式化
    vue入门之单文件组件
    Echarts图表-学习
    GoJS学习
  • 原文地址:https://www.cnblogs.com/panini/p/6400691.html
Copyright © 2011-2022 走看看