Leetcode 69 Sqrt(x) 二分查找(二分答案)
可怕的同时考数值溢出和二分的酱油题之一,常在各种小公司的笔试中充当大题来给你好看。。。
题意很简单,在《二分查找综述》中有描述。
重点:使用简单粗暴的long long来避免溢出,二分均方根的答案来得到准确解。
当然这里的溢出不止是相乘的溢出,还有第六行那段代码的溢出,每次都会有几个解决问题的斗士牺牲在这里。。。
class Solution {
public:
int mySqrt(int x) {
long long a = , b = x;
while(a <= b ){
long long mid = a + (b - a) /;
if(mid * mid == x) return mid;
if(mid * mid < x ) a = mid + ;
else b = mid - ;
}
return (int)b;
}
};
这里已经给出了两种题目的解法,相信大家对于二分查找有了一个比较清晰的认识,可以写一个关于二分查找的模板了,但是懒惰楼主是不会写的。。。
Leetcode 69 Sqrt(x) 二分查找(二分答案)的更多相关文章
- Leetcode 69. Sqrt(x)及其扩展(有/无精度、二分法、牛顿法)详解
Leetcode 69. Sqrt(x) Easy https://leetcode.com/problems/sqrtx/ Implement int sqrt(int x). Compute an ...
- (二分查找 拓展) leetcode 69. Sqrt(x)
Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a no ...
- C++版 - Leetcode 69. Sqrt(x) 解题报告【C库函数sqrt(x)模拟-求平方根】
69. Sqrt(x) Total Accepted: 93296 Total Submissions: 368340 Difficulty: Medium 提交网址: https://leetcod ...
- [LeetCode] 69. Sqrt(x) 求平方根
Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a no ...
- LeetCode 69. Sqrt(x) (平方根)
Implement int sqrt(int x). Compute and return the square root of x. x is guaranteed to be a non-nega ...
- Leetcode 69. Sqrt(x)
Implement int sqrt(int x). 思路: Binary Search class Solution(object): def mySqrt(self, x): "&quo ...
- [LeetCode] 69. Sqrt(x)_Easy tag: Binary Search
Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a no ...
- 【leetcode边做边学】二分查找应用
很多其它请关注我的HEXO博客:http://jasonding1354.github.io/ 简书主页:http://www.jianshu.com/users/2bd9b48f6ea8/lates ...
- python函数(4):递归函数及二分查找算法
人理解循环,神理解递归! 一.递归的定义 def story(): s = """ 从前有个山,山里有座庙,庙里老和尚讲故事, 讲的什么呢? ""& ...
随机推荐
- C# 获取本机指定类型指定网卡的Ip地址
1.简单方式 ,适用于单网卡 string hostName = Dns.GetHostName(); IPAddress[] addresses = Dns.GetHostAddresses(hos ...
- Linq-分组统计
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...
- 【转】Backbone使用总结
转自 http://www.pchou.info/javascript/2014/06/26/backbone-summary-01.html 开始在项目中大规模使用backbone,一路磕磕碰碰, ...
- TreeMap源码分析
MapClassDiagram
- 编译系统中的LR与LL理解
编译原理:LL(1),LR(0),SLR(1),LALR(1),LR(1)对比 LL(1)定义:一个文法G是LL(1)的,当且仅当对于G的每一个非终结符A的任何两个不同产生式 A→α|β,下面的条件成 ...
- Linq To Xml基础
<?xml version="1.0" encoding="utf-8" ?> <Books> <Category Order=& ...
- 对bit、byte、TByte、Char、string、进制的认识
在学校老师就教1byte = 8bit,一个Byte在内存中占8个房间.每个房间都有门牌号.找到内存中的内容就找门牌号,寻址什么的,虽然在听,但是脑袋里一头雾水,到现在只知道会用就行,但原理也不是那么 ...
- 关于windows phone教务在线客户端
本人是个大二学生,由于学校的教务在线一直没出windows phone的教务在线,而且本身也对wp开发感兴趣,所以就尝试着开发一下 由于没有系统的学习,只能在摸索中前进,这背后的原理很简单,可不容易实 ...
- CentOS7 bonding配置
操作系统:CentOS Linux release 7.1.1503 (Core) 网卡适配器: eno1.eno2 bonding类型:mode=1 (active-backup),主-备份策略 网 ...
- shell 知识
解压 tar.bz2文件 bunzip2 linux-2.6.13.tar.bz2 | tar xvf -