Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

题目标签:Math

  题目给了我们一个x, 让我们找到平方根。

  可以利用binary search 来做,首先找到一个范围,不需要是从0 到 x。因为 sqrt(x) 一定是小于等于 x / 2 + 1的。

  所以起始范围为 0  到  x / 2 + 1;

  还要注意 sq = mid * mid。 这里要检查 overflow。

Java Solution:

Runtime beats 53.10%

完成日期:06/12/2017

关键词:Binary Search

关键点:检查overflow

 class Solution
{
public int mySqrt(int x)
{
int left = 0;
int right = x / 2 + 1; while(left <= right)
{
int mid = left + (right - left)/2;
int sq = mid * mid; if(mid != 0 && sq / mid != mid) // check overflow
{
right = mid - 1; // meaning mid is too big, go to left part
continue;
} if(sq == x)
return mid;
else if(sq < x)
left = mid + 1;
else
right = mid - 1; } return right;
}
}

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

最新文章

  1. 网页制作中在头部固定悬浮table表头(thead)的方法
  2. 如何直接在ftp里编辑文件
  3. C#之事件
  4. 关于时区的时间的详解,比如UTC\GMT等
  5. 与IO相关的等待事件troubleshooting-系列9
  6. 8.2.1.3 Range Optimization
  7. JS 的NULL undefined 空
  8. AS3条件编译
  9. c# RSA加密和解密
  10. [poj2923]Relocation_状压dp_01背包
  11. Postman 安装及使用入门教程(我主要使用接口测试)
  12. Java -- 构造函数 &amp; this &amp; 方法重写和方法重载的区别
  13. 读取Excel,单元格内容大于255个字符自动被截取的问题
  14. 安装GDB-ImageWatch ,在QT中查看图像
  15. InputStream流无法重复读取的解决办法
  16. PHP 命令行模式实战之cli+mysql 模拟队列批量发送邮件(在Linux环境下PHP 异步执行脚本发送事件通知消息实际案例)
  17. Mail.Ru Cup 2018 Round 1
  18. Mac PHPStorm快捷键总结
  19. git与pycharm合并,珠联璧合
  20. Saw a tweet from Andrew Liam Trask, sounds like Oxford DeepNLP 2017 class have all videos slides practicals all up. Thanks Andrew for the tip!

热门文章

  1. Android电池电量跳变
  2. ios 布局 素材 待整理
  3. QuickClip—界面原型设计
  4. 00HyperText Markup Language
  5. vue-quill-editor富文本焦点问题
  6. svn更新报错Please execute the &#39;Cleanup&#39; command.
  7. scala学习(1)----map和flatMap的区别
  8. 数据结构---链表ADT C++实现
  9. TestNG异常测试
  10. 【Codeforces 372A】Counting Kangaroos is Fun