[Leetcode] Sqrt(x)
来源:互联网 发布:东北大学奥鹏网络教育 编辑:程序博客网 时间:2024/06/10 17:07
题目:
Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:二分法,注意溢出,需要将乘积换成long long型。
class Solution {public: int sqrt(int x) { if (x < 0) return -1; long long lower_bound = 0; long long upper_bound = x; long long target = x; while (lower_bound <= upper_bound) { long long mid = (lower_bound + upper_bound) / 2; long long temp_product = mid * mid; if (temp_product == target || (temp_product < target && (mid + 1) * (mid + 1) > target)) { return (int)mid; } else if (temp_product < x) { lower_bound = mid + 1; } else { upper_bound = mid - 1; } } }};
总结:复杂度O(log n).
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)
- 小贝学习html--表格
- html hover 实用例子
- 【MS SQL Server】SQL删除数据的各种方式总结
- 文件输入输出小程序 改变所有逗号为冒号 fscanf fprintf
- main 函数的参数
- [Leetcode] Sqrt(x)
- 如何用Labview开发WinCE触摸板程序
- poj 1318 Word Amalgamation
- 【MS SQL Server】使用【数据库收缩功能】实现多个数据文件的合并
- myeclipse安装反编译插件jdeclipse
- 设计模式(1)
- Android 系统中运行独立 c 语言 udp 程序
- 【MS SQL Server】sql server 创建作业
- 设计模式(2)