leetcode [Sqrt(x)]
来源:互联网 发布:学linux能干哪些工作 编辑:程序博客网 时间:2024/04/26 02:50
二分搜索法求平方根:
public class Solution { public int mySqrt(int x) { //既然是寻找一个数的平方根,就属于查找的方式,查找中有二分查找法 //二分查找法求平方根,记住算法,无限逼近 if (x == 0) return 0; int left = 1, right = x, ans = 0; while (left <= right) { int mid = (left + right) / 2; if(mid == x / mid) return mid; if (mid < x / mid) {//不能写成if (mid * mid < x),否则当mid大于sqrt(x)时会溢出 left = mid + 1; ans = mid; } else { right = mid - 1; //ans = mid; 这一句不要,因为返回的是整型,开方取地板,所以ans放在if(mid < x / mid)那里 } } return ans; }}
牛顿迭代算法:
class Solution { public int mySqrt(int x) { //牛顿迭代算法求平方根,记住 long r = x; while (r * r > x) r = (r + x / r) / 2; return (int) r; }}
0 0
- LeetCode: Sqrt(x)
- LeetCode sqrt(x)
- [Leetcode] Sqrt(x)
- LeetCode :Sqrt(x)
- leetcode 53: Sqrt(x)
- [LeetCode] Sqrt(x)
- Leetcode 69 sqrt(x)
- [Leetcode] Sqrt(x)
- leetcode:Sqrt(x)
- 【leetcode】sqrt(int x)
- [LeetCode]Sqrt(x)
- [leetcode]Sqrt(x)
- LeetCode-Sqrt(x)
- [leetcode] Sqrt(x)
- [leetcode] Sqrt(x)
- LeetCode - Sqrt(x)
- leetcode之sqrt(x)
- LeetCode | Sqrt(x)
- android蓝牙4.0的知识要点
- 【第12题】360校园招聘2015届技术类笔试题
- Lambda&Java多核编程-5-函数式接口与function包
- POJ3709 K-Anonymous Sequence(k匿名序列)(斜率优化dp)
- PAT-练习集-L1-025. 正整数A+B
- leetcode [Sqrt(x)]
- codeforces 782B
- C语言 strnlen函数实现
- 【第13题】360校园招聘2015届技术类笔试题
- Android注解使用之ButterKnife 8.0注解使用介绍
- 【贪心算法】最少拦截系统
- 重温数据结构一
- CSS中的背景用法大全
- 【第14题】360校园招聘2015届技术类笔试题