LeetCode做题笔记 - 69 - X的平方根(简单)
题目:求x的平方根(难度:简单)
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
思路
只用精确到整数(直接舍弃小数,不是四舍五入)。用二分法搜索。取x的一半x/2,求x/2的平方,跟x比较。如果小,则继续在后半部分搜索;如果大,则继续在前半部分搜索;相等则直接返回。
考虑到算平方的时候,可能超出int范围,因此用double。
代码
class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
if (x < 4) return 1; // 较小的情况直接返回,避免二分出错
int lower = 0;
int higher = x;
while (higher > lower+1) // 结束循环的条件是搜索范围变为1
{
double mid = (higher + lower) / 2;
if (mid*mid == x)
{
return (int)mid;
}
else if (mid*mid > x)
{
higher = mid;
}
else
{
lower = mid;
}
}
return lower; // 精确到整数,取较小的
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】