leetcode—sqrt
1.题目描述
Implement int sqrt(int x).Compute and return the square root of x.
2.解法分析
很明显,用二分搜索可解,但是需要防止溢出,所以中间结果和上界下界都要用long long 来保存。
class Solution {public:int sqrt(int x) {// Start typing your C/C++ solution below// DO NOT write int main() functionif(x<0)return -1;if(x<4)return x>0?1:0;long long rmin=0;long long rmax=x/2;long long rmid;while(rmin<rmax){rmid=(rmin+rmax)/2;if((rmid*rmid)==x)return rmid;if((rmid*rmid)<x)rmin=rmid+1;else rmax=rmid-1;}int result=rmin;while(result*result>x)result--;return result;}};
leetcode—sqrt的更多相关文章
- [LeetCode] Sqrt(x) 求平方根
Implement int sqrt(int x). Compute and return the square root of x. 这道题要求我们求平方根,我们能想到的方法就是算一个候选值的平方, ...
- [leetcode]Sqrt(x) @ Python
原题地址:https://oj.leetcode.com/problems/sqrtx/ 题意: Implement int sqrt(int x). Compute and return the s ...
- Leetcode Sqrt(x)
参考Babylonian method (x0 越接近S的平方根越好) class Solution { public: int sqrt(double x) { ) ; , tolerance ...
- LeetCode: Sqrt
Title: Implement int sqrt(int x). Compute and return the square root of x. 思路:这个平方根肯定是在[1,x]之间,所以在这个 ...
- LeetCode:Sqrt(x) 解题报告
Sqrt(x) Implement int sqrt(int x). Compute and return the square root of x. SOLUTION 1: 参见:二分法总结,以及模 ...
- LeetCode——Sqrt(x)
Description: Implement int sqrt(int x). Compute and return the square root of x. 好好学习数学还是非常有用的,牛顿迭代法 ...
- [Leetcode] sqrt 开根号
Implementint sqrt(int x). Compute and return the square root of x. 题意:求根号下x 的值 思路:使用二分搜索.先定义x平方根的取值区 ...
- [LeetCode] Sqrt(x) 二分搜索
Implement int sqrt(int x). Compute and return the square root of x. Hide Tags Math Binary Search ...
- LeetCode 解题报告索引
最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
随机推荐
- python 字符串格式化 输出
1. 需要输出3列,为了输出好看,需要制定每一列的宽度: ‘%6.2f’ % 1.235 # 长度为6,保留2为小数 print '{0:20} {1:<20} {1:<20}\r\n'. ...
- 给360的六条建议(禁止异地登录,普通用户500G足够用了)
个人觉得,360云盘哪怕做个小改进,都不至于走到现在的地步,最后六条建议! 1.弄个实名制,身份证和手机号码双重绑定,每人限制申请一个账户. 2.禁止云盘的一切分享功能,采用封闭式,个人云盘资料其他人 ...
- Generic Data Access Layer泛型的数据访问层
http://www.codeproject.com/Articles/630277/Generic-Data-Access-Layer-GDA-Part-I http://www.codeproje ...
- 面试题_66_to_75_Java IO 和 NIO 的面试题
IO 是 Java 面试中一个非常重要的点.你应该很好掌握 Java IO,NIO,NIO2 以及与操作系统,磁盘 IO 相关的基础知识.下面是 Java IO 中经常问的问题. 66)在我 Java ...
- webbrowser代理c#代码实现
微软webbrowser控件也就是IE插件,他的所有功能就像IE类似,当然设置也是一样的,下面介绍下webbrowser如何设置代理,可不要用这个对抗广告联盟哦 You can change the ...
- 2014年百度之星程序设计大赛 - 资格赛 1004 Labyrinth(Dp)
题目链接 题目: Labyrinth Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Other ...
- 函数get_table_share
得到一个table_share 1)先从table_def_cache中查找, 如果有, 直接返回 2)如果没有找到, 为table_share分配内存,初始化,打开.frm文件,并将share ...
- bzoj2535 2109
做过4010这题其实就水了 把图反向之后直接拓扑排序做即可,我们可以用链表来优化 每个航班的最小起飞序号就相当于在反向图中不用这个点最迟到哪 type node=record po,next:long ...
- Asp.Net连接Mysql报错Out of sync with server
Asp.Net连接Mysql报错Out of sync with server 原因:程序引用的MySql.Data.dll版本高于服务器版本 解决:下载一个低版本的MySql.Data.dll,项目 ...
- [swustoj 1023] Escape
Escape Description BH is in a maze,the maze is a matrix,he wants to escape! Input The input cons ...