LEETCODE,leetcode—sqrt

 2023-11-09 阅读 26 评论 0

摘要:1.題目描述 ? Implement int sqrt(int x). ? Compute and return the square root of x. LEETCODE。2.解法分析 很明顯,用二分搜索可解,但是需要防止溢出,所以中間結果和上界下界都要用long long 來保存。 class Solution { public: int sqrt(int x) { /

1.題目描述

?

Implement int sqrt(int x).
?
Compute and return the square root of x.

LEETCODE。2.解法分析

很明顯,用二分搜索可解,但是需要防止溢出,所以中間結果和上界下界都要用long long 來保存。

class Solution {
public:
    int sqrt(int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(x<0)return -1;
        if(x<4)return x>0?1:0;
        long long  rmin=0;
        long long  rmax=x/2;
        
        long long  rmid;
        
        while(rmin<rmax)
        {
            rmid=(rmin+rmax)/2;
            if((rmid*rmid)==x)return rmid;
            if((rmid*rmid)<x)rmin=rmid+1;
            else rmax=rmid-1;
        }
        
        int result=rmin;
        while(result*result>x)result--;
        
        return result;
        
    }
};

轉載于:https://www.cnblogs.com/obama/p/3285058.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/168282.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息