leetcode sqrt
来源:互联网 发布:淘宝仅退款不退货规则 编辑:程序博客网 时间:2024/05/17 21:07
这题是给出一个x,求平方根。
一种直接二分,一种牛顿迭代求不动点。
二分:
class Solution {public: bool isAns(long long r, long long x) { if (r*r<=x && (r + 1)*(r + 1)>x) return true; return false; } int mySqrt(int x) { if (x <= 0) return 0; long tar = x; long long low = 0,high= x; long long mid = low + (high - low) / 2; while (!isAns(mid, tar)) { if ((mid + 1)*(mid + 1) <= tar) { low = mid+1; } else{ high = mid-1; } mid = low + (high - low) / 2; } return mid; }};
牛顿法:
#include <math.h>class Solution{public: int mySqrt(int x) { if (x <= 0) return 0; double init = x / 2.0; double ans = init* 0.5 + x / (2 * init); while (fabs(ans - init) > 0.005) { init = ans; ans = init* 0.5 + x / (2 * init); } return (int)ans; }};
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)
- Android— Android中十六进制颜色字符串转int的方法
- 微软100题(78)链表和数组的区别
- MySQL转换Oracle的注意事项
- UITableView的简单介绍和功能
- LeetCode 之 Longest Common Prefix — C++实现
- leetcode sqrt
- java 并发编程 AbstractQueuedSynchronizer 加锁和解锁分析
- iOS 分享功能开发
- sshutil工具介绍:一个跨机器的脚本执行器
- #leetcode#Candy
- IBM---Java 多线程与并发编程专题
- 【Leetcode Algorithm】Roman to Integer
- IM消息的显示方法和装置-专利
- 总结:接口、类、抽象类、继承、构造函数、方法重写、方法重载、自动转型、多态、引用传递