Leetcode NO.69 Sqrt(x)
来源:互联网 发布:藏民对十一世班禅 知乎 编辑:程序博客网 时间:2024/05/01 02:54
题目要求如下:
Implement int sqrt(int x)
.
Compute and return the square root of x.
题意就是自己implement一个sqrt()函数,不过input,output都是int型,就是返回整数(不是四舍五入),比如sqrt(3) = 1我写的代码如下:
class Solution {public: int sqrt(int x) { if (x <= 0) return 0; else if (x == 1) return 1; else { int low = 1; int high = x; int mid; while (low <= high) { mid = (high + low) / 2; if (mid <= x / mid && (mid+1) > x / (mid+1)) return mid; else if (mid > x / mid) high = mid - 1; else low = mid + 1; } } }};
本质上就是个binary search,
(1)如果mid * mid <= x, 并且(mid+1)*(mid+1)<x,则mid即为该值
(2)如果mid*mid > x,则舍弃所有大于mid的值,将high置于mid - 1
(3)如果(mid+1)*(mid+1)<=x,则舍弃所有小于mid的值,low置于mid+1
0 0
- Leetcode NO.69 Sqrt(x)
- LeetCOde No.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)
- 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)
- Reverse Integer
- GridView如何适配不同屏幕
- 阻尼回弹效果的ScrollView嵌套GridView
- 设计模式学习笔记五:抽象工厂模式
- 高职生制专业“双师型”教师队伍发展的策略
- Leetcode NO.69 Sqrt(x)
- 设计模式学习笔记六:原型设计模式
- leedcode做题总结, 题目Longest Palindromic Substring 5
- 《从Paxos到ZooKeeper:分布式一致性理论与实践》上市了
- top.index
- linux下给普通用户增加权限
- Linkedin工程师是如何优化他们的Java代码的
- (转载) IO - 同步,异步,阻塞,非阻塞 (亡羊补牢篇)
- SQL Server评估期已过问题