1、题目

Implement int sqrt(int x).

Compute and return the square root of x.

Subscribe to see which companies asked this question.

2、代码实现

public class Solution {public int mySqrt(int x) {if (x < 0)return -1;if (x == 0)return 0; if (x == 1) return 1;int max = x / 2 + 1;int min = 1;while (min <= max) {int mid = (min + max) / 2;if (mid <= x / mid && x / (mid + 1) < mid + 1)return mid;if (mid > x / mid) max = mid - 1;elsemin = mid + 1;}return 0;}
}

3、注意的地方

1)、第一要记得判断条件是 
mid * mid <= x && (mid + 1) * (mid + 1) >x 
2)、第二要防止数据超过整形数据范围,所以需要把条件转化为

mid <= x / mid && x / (mid + 1) < mid + 1
3)、逻辑要清晰,先求max,min, next we will get mid, and condition is mid * mid <= x && (mid + 1) * (mid + 1) > x, and by condition ,do not remember max = mid -1, min = mid +1 or max = mid, min = mid;

LeetCode之Sqrt(x)相关推荐

  1. 【分治】LeetCode 69. Sqrt(x)

    LeetCode 69. Sqrt(x) 参考网址:http://www.cnblogs.com/grandyang/p/4346413.html Solution1: class Solution ...

  2. LeetCode 69. Sqrt(x)

    题目: Implement int sqrt(int x). Compute and return the square root of x. 思路: 写一个自己的求平方根的函数. 初始化low为0, ...

  3. LeetCode 69: Sqrt(x) 求根号x(牛顿迭代法和二分查找法)

    题目: Implement int sqrt(int x). Compute and return the square root of x. 分析:我们平常可能好少会自己去求解某个数的平方根,一般都 ...

  4. Leetcode 69 Sqrt(x)

    Implement int sqrt(int x). Compute and return the square root of x. 求x的平方根. 二分没什么好说的,注意INT_MAX溢出的情况! ...

  5. LeetCode(69)Sqrt

    题目如下: Implement int sqrt(int x). Compute and return the square root of x. 分析如下: (1)借助一个小结论,任何一个数的squ ...

  6. LeetCode | 69. Sqrt(x)

    Implement int sqrt(int x). Compute and return the square root of x. 很简单的题: class Solution { public:i ...

  7. LeetCode:69. Sqrt(x)

    题目链接: 69. Sqrt(x) 题目描述: Implement int sqrt(int x) Compute and return the square root of x. 题目解释: 提干非 ...

  8. LeetCode——[69] Sqrt(x)

    int mySqrt(int x) {int i = 1;while(i*i <=x)i++;return --i;} 可把你给厉害坏了.脚趾头想也想到了结局. ✘ Runtime Error✘ ...

  9. LeetCode:69.Sqrt

    题目描述: 给你一个非负整数 x ,计算并返回 x 的 算术平方根 . 由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 . 注意:不允许使用任何内置指数函数和算符,例如 pow(x, ...

最新文章

  1. P1203 [USACO1.1]坏掉的项链Broken Necklace
  2. 【转载】你真的了解补码吗
  3. Python基础练习题合集
  4. java保留有效数字
  5. pycharm无法导入本地模块问题
  6. 深度相机---(2)结构光深度测距
  7. 汉字与区位码互转(转)
  8. Android历史与版本变迁
  9. 人工神经网络可以做什么,人工神经网络有什么用
  10. Android6.0之AMS启动app中篇之创建app进程
  11. pytecplot 的安装与启动(tecplot GUI能用但是pytecplot不能用)
  12. r语言 聚类求和_R语言聚类分析(示例代码)
  13. 用c语言编译频率求波长,频率与波长的换算公式(c=λv)
  14. python 程序员待遇_python程序员待遇如何
  15. tensorflow gpu环境安装
  16. echarts省级地图显示(入门)
  17. 以指标驱动业务决策,Kyligence 亮相 Gartner IT Symposium/Xpo™ 峰会
  18. WinCC flexible Smart V3 SP2软件安装具体方法和步骤_常见问题处理
  19. C基础的ObjectiveC学习
  20. 计算机组成,南北桥,倍频,通信,频率一致才可以通信

热门文章

  1. 为什么 Linux 上的 Asp.NET 5 需要 Kestrel ?
  2. 微软加入字节码联盟,进一步开发支持Blazor 的WebAssembly技术
  3. .NET 中依赖注入组件 Autofac 的性能漫聊
  4. 你有把依赖注入玩坏?
  5. ASP.NET Core 依赖注入-集成 Autofac
  6. ABP VNext从单体切换到微服务
  7. 我们真的需要JWT吗?
  8. 从零开始内建你的安全测试流程
  9. iPhone上运行Linux也要来了
  10. 在.NET中执行Async/Await的两种错误方法