Leetcode : Sqrt
来源:互联网 发布:js组合sophia病逝 编辑:程序博客网 时间:2024/05/18 00:36
url :
https://leetcode.com/problems/sqrtx/description/
描述
Implement int sqrt(int x).
Compute and return the square root of x.
思路二分法
代码
/** * Created by hadoop on 17-10-3. */public class MySqrt { public int mySqrt(int x) { return (int)sqrtHelper2(x); }//非递归 private long sqrtHelper2(int x){ long start = 0; long end = x; long mid = 0; long temp = 0; long res = -1; while(start <= end) { mid = (start+end)/2; temp = mid * mid; if(temp == x) { res = mid; break; }else if(temp > x){ end = mid-1; }else { start = mid+1; res = mid; } } return res; }//递归 private long sqrtHelper(long start, long end, int x) { if (start > end) return -1; long mid = (start + end) / 2; if (mid * mid == x) {//注意mid乘积之后数值的取值范围,这里使用long类型 return mid; } else if (mid * mid < x) { long temp = sqrtHelper(mid + 1, end, x); if (temp == -1) { return mid; } else { return temp; } } else { long temp = sqrtHelper(0, mid-1 , x); if(temp == -1){ return mid; }else{ return temp; } } }//测试 public static void main(String[]args){ MySqrt mySqrt = new MySqrt(); int x = mySqrt.mySqrt(2147395599); System.out.println(x); }}
阅读全文
0 0
- Leetcode: sqrt
- leetcode sqrt
- Leetcode-sqrt
- 【leetcode】sqrt
- [LeetCode] Sqrt
- Leetcode : Sqrt
- 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(int num)
- [Leetcode] Sqrt(x)
- leetcode:Sqrt(x)
- 【leetcode】sqrt(int x)
- [LeetCode]Sqrt(x)
- IDEA异常 cannot resolve symbol 'HttpServletRequest'
- 数论逆元
- 在Windows下通过notepad++分别运行python2.x和python3.x
- 源代码版本安装intl扩展库
- LVS负载均衡群集—DR
- Leetcode : Sqrt
- iOS 数组~arraywithcapacity方法
- 想了解Java多线程,此篇文章足矣!
- 【LibUIDK界面库系列文章】指定ComboBox的高度
- kali 局域网断网攻击
- 剑指Offer------变态跳台阶
- 数据库优化-- 设计阶段
- Directx9学习(九)碰撞——基于边界和基于距离
- 【Spring】引入(一)