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,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
随机推荐
- NPOI技术,
using(FileStream stream=new FileStream("C:\Users\XXXXXX\Desktop\1.xls",FileMode.Open)) ...
- 关于use-default-filters的一个问题
use-default-filters=true 默认行为会自动扫描所有注解
- 5、处理模型数据ModelAndView、Map、Model以及@SessionAttributes注解
Spring MVC提供了以下几种途径输出模型数据 —— ModelAndView: 处理方法返回值类型为ModelAndView时,方法体即可通过该对象添加模型数据.数据会添加到request域中. ...
- 转:java两个jre目录和三个lib目录
lib目录下放置着jar包.程序中的import语句找的就是这些文件!例如:import javax.servlet.RequestDispatcher; 问题在于,在cmd模式下编译,系统会提 ...
- (贪心5.2.1)UVA 10026 Shoemaker's Problem(利用数据有序化来进行贪心选择)
/* * UVA_10026.cpp * * Created on: 2013年10月10日 * Author: Administrator */ #include <iostream> ...
- CocoaPods requires your terminal to be using UTF-8 encoding
WARNING: CocoaPods requires your terminal to be using UTF-8 encoding. See https://github.com/CocoaPo ...
- 各浏览器各版本User-agent汇总 欢迎补充
Internet Explorer Internet Explorer 5 Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; WOW64; Trident/ ...
- bzoj1797: [Ahoi2009]Mincut 最小割
最大流+tarjan.然后因为原来那样写如果图不连通的话就会出错,WA了很久. jcvb: 在残余网络上跑tarjan求出所有SCC,记id[u]为点u所在SCC的编号.显然有id[s]!=id[t] ...
- BZOJ3858: Number Transformation
题目:http://www.lydsy.com/JudgeOnline/problem.php?id=3858 题解:设第i个数为i*a;第i+1个数为(i+1)*b.则(i+1)*b>i*a; ...
- codevs 3290 华容道
HAHAHA BFS+SPFA. #include<iostream> #include<cstdio> #include<cstring> #include< ...