美文网首页
LeetCode-Sqrt(x)

LeetCode-Sqrt(x)

作者: 圣地亚哥_SVIP | 来源:发表于2018-11-01 11:27 被阅读0次

这是一道easy的题目,主要注意点是数据溢出的问题,以下有两种解法:

1 x >= (ans * ans) && x < (ans+1)*(ans+1)return ans;这里要考虑溢出,所以ans数据类型要为long long
2 pre = x/ans if (pre < ans)return ans-1; 这里就无需考虑溢出

Solution1:
class Solution {
public:
    int mySqrt(int x) {
        if (x==0)return 0;
        int ans = 1;
        while(true){
            long long  pre = ans * ans;
            long long pos = pre+2*ans +1;
            if (pre<=x && x< pos){
                return ans;
            }
            ans++;
        }
    }
};

Solution2:
class Solution {
public:
    int mySqrt(int x) {
        if (x==0)return 0;
        int ans = 1;
        while(true){
            int pre = x/ans;
            if (pre < ans)return ans-1;
            ans++;
        }
    }
};

相关文章

网友评论

      本文标题:LeetCode-Sqrt(x)

      本文链接:https://www.haomeiwen.com/subject/zbgtxqtx.html