leetcode 69 Sqrt
来源:互联网 发布:java防止api重复提交 编辑:程序博客网 时间:2024/06/15 14:07
/** * Created by 短裤内穿的超人 on 2017/9/26. * title: leetcode 69 * 基本描述:69 实现sqrt(x)函数的功能 * * 解题思路: * 这些题基本都是考察二分搜索,也就是折半查找,这有几个坑要特别注意,一个是终结条件,left>right * 还有一个是更新条件,以及求中位数注意溢出 */public class BinarySearch { public static int mySqrt(int x) { if(x == 0) return 0; int left = 1; int right = x; int mid,ans = 0; while(left <= right){ mid = left+(right-left)/2; //这里用这种表述主要是为了防止right+left超过整形范围溢出 if(mid == (x / mid)) return mid; //同样不用mid*mid也是为了防止溢出 else if(mid < (x / mid)){ ans = mid; //这边用ans来记录隐形的答案 left = mid+1; //二分搜索的更新条件不能用left=mid等为出现死循环 }else{ right = mid-1; } } return ans; } public static void main(String[] args){ int x = 2147395599; //-123 int ans = BinarySearch.mySqrt(x); System.out.println(ans); }}
阅读全文
0 0
- Leetcode 69 sqrt(x)
- LeetCode(69)Sqrt
- leetcode 69 Sqrt(x)
- [leetcode 69] Sqrt(x)
- [leetcode] 69 Sqrt(x)
- leetcode-69 Sqrt(x)
- LeetCode 69 Sqrt(x)
- leetcode || 69、Sqrt(x)
- LeetCode 69 Sqrt(x)
- LeetCode-69 Sqrt(x)
- Sqrt(x) - LeetCode 69
- leetcode 69:Sqrt(x)
- LeetCode---(69)Sqrt(x)
- Leetcode #69 Sqrt(x)
- LeetCode(69) Sqrt(x)
- leetcode 69: Sqrt(x)
- Leetcode#69||Sqrt(x)
- [Leetcode]#69 Sqrt(x)
- 数据可视化1---直方图-折线图
- Android实例程序中Gallery报错:R.styleable unresolved解决办法
- 有用的网址
- ssm框架集成Quartz定时器
- 小度鱼(React-Native)
- leetcode 69 Sqrt
- 教你Mac OS系统四种修改Hosts文件的方法
- Erlang Unicode 两三事
- Oracle流程控制语句
- ES6(十: import 模块加载)
- Scala学习笔记
- POJ 3615 Cow Hurdles
- Django REST framework-教程02-Requests and Responses原创翻译
- 自定义控件的使用