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; // 精确到整数,取较小的
    }
};
posted @   星夜之夏  阅读(148)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 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】
点击右上角即可分享
微信分享提示