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,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
随机推荐
- nslookup工具的使用方法
配置好DNS服务器,添加了相应的记录之后,只要IP地址保持不变,一般情况下我们就不再需要去维护DNS的数据文件了.不过在确认域名解释正常之前我们最好是测试一下所有的配置是否正常.许多人会简单地使用pi ...
- Flex 国际化(flex Localize)
先说编译到主程序中去的方法: 1.创建资源文件夹 譬如可以在src文件夹下创建Locale文件夹,然后在此文件夹再次创建每个地区的资源文件夹,譬如de_DE,zh_CN. 然后分别创建后缀名为.pro ...
- PHP5.4连接sqlserver
1.下载微软的php连接驱动:SQLSRV30.EXE(5.4对应,后面的native client要用2012)/SQLSRV20.EXE(5.3对应,native client要用2008)/SQ ...
- php整理(一):变量和字符串
PHP中的变量: 1. 定义:$符号来定义变量 2. 说明: (1)PHP弱语言,定义变量的时候不用声明类型,但是并不代表PHP没有数据类型 (2)变量名是区分大小写的,只能是数字,字母或者下划线 ( ...
- C++ STL之list容器的基本操作
由于list和vector同属于序列式容器,有很多相同的地方,而上一篇中已经写了vector,所以这一篇着重写list和vector的不同之处和特有之处. 特别注意的地方: (1)STL中迭代器容器中 ...
- 国内顺利使用Google的另类技巧
在特殊的地方和特殊的时间,流畅顺利使用Google的方法也会变得很特殊.本文不定期保持维护更新,删除不能用的,增加新的网址. 分享一些奇葩的Google使用方法,通过下列网址也可以使用Google来搜 ...
- UVa 11542 (高斯消元 异或方程组) Square
书上分析的太清楚,我都懒得写题解了.=_=|| #include <cstdio> #include <cstring> #include <cmath> #inc ...
- BZOJ1048: [HAOI2007]分割矩阵
题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1048 题解:搞清题意之后来个记忆化爆搜就行了. 代码: #include<cstdio& ...
- 8 种 NoSQL 数据库系统对比
导读:Kristóf Kovács 是一位软件架构师和咨询顾问,他最近发布了一片对比各种类型NoSQL数据库的文章. 虽然SQL数据库是非常有用的工具,但经历了15年的一支独秀之后垄断即将被打破.这只 ...
- Android ArrayAdapter 详解
本文主要讲解ArrayAdapter的创建方法,我把ArrayAdapter分为三种:简单的.样式丰富的但内容简单的.内容丰富的. 默认的,ArrayAdapter期望接受的样式文件里只含有一个tex ...