[LeetCode] Sqrt(x)
2015-08-22 22:27
369 查看
Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x.
题目的意思是找x的平方根,思路也是比较简单 是使用二分法查找
关键在比较时有个问题不能使用mid*mid与x比较,因为可能溢出
而是应该使用mid与x/mid
Implement int sqrt(int x).
Compute and return the square root of x.
题目的意思是找x的平方根,思路也是比较简单 是使用二分法查找
关键在比较时有个问题不能使用mid*mid与x比较,因为可能溢出
而是应该使用mid与x/mid
class Solution { public: int mySqrt(int x) { if(x==0||x==1) return x; int left = 1; int right = x/2+1; int mid; while(1){ //mid = (right + left)/2; mid = left + (right - left)/2; //to prevent overflow if(mid> x/mid) right = mid-1; else if(mid + 1 > x/(mid + 1)) return mid; else left = mid+1; } } };
相关文章推荐
- leetcode 113. Path Sum II (路径和) 解题思路和方法
- android与服务器之间数据通信(struts2+JSON+android)
- UpdateLayeredWindow是炫效果的关键
- 通俗易懂的Nhibernate教程(1) ----- 基本操作,映射,CURD
- 从零开始学Java 有关线程的学习总结
- 小端与大端
- HDU 5418 Victor and World(状态压缩路径DP或+floyd 两种方法 求 玈行商问题)经典
- c++中构造函数和析构函数执行过程
- 一些简单的命令使用
- CSS BOX模型
- bash基础-其他配置文件和登录信息
- charles抓接口步骤
- CSS BOX模型
- 浅谈GCD(Grand Central Dispatch)
- POJ 1330 ---(线段树在线LCA 与 tarjan离线LCAs)
- HDU 2612 Find a way
- c# OpenFileDialog
- VMware搭建虚拟机安装redis并实现局域网通信
- NumPy常用【数值计算】函数总结(1):生成数组、读取数组、数组操作
- poj 3660 Cow Contest floyd