LeetCode 69. Sqrt(x) (平方根)
2024-08-30 23:33:11
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/
最新文章
- 网页制作中在头部固定悬浮table表头(thead)的方法
- 如何直接在ftp里编辑文件
- C#之事件
- 关于时区的时间的详解,比如UTC\GMT等
- 与IO相关的等待事件troubleshooting-系列9
- 8.2.1.3 Range Optimization
- JS 的NULL undefined 空
- AS3条件编译
- c# RSA加密和解密
- [poj2923]Relocation_状压dp_01背包
- Postman 安装及使用入门教程(我主要使用接口测试)
- Java -- 构造函数 &; this &; 方法重写和方法重载的区别
- 读取Excel,单元格内容大于255个字符自动被截取的问题
- 安装GDB-ImageWatch ,在QT中查看图像
- InputStream流无法重复读取的解决办法
- PHP 命令行模式实战之cli+mysql 模拟队列批量发送邮件(在Linux环境下PHP 异步执行脚本发送事件通知消息实际案例)
- Mail.Ru Cup 2018 Round 1
- Mac PHPStorm快捷键总结
- git与pycharm合并,珠联璧合
- 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!