牛客题霸 [求平方根] C++题解/答案

牛客题霸 [求平方根] C++题解/答案

题目描述

实现函数 int sqrt(int x).
计算并返回x的平方根

题解:

要求返回平方根,我们就找一个i,使得ii<=x&&(i+1)(i+1)>x
这样的i就是我们要找的答案
注意,x有可能为负数,当<=0时返回0

代码:

class Solution {
public:
    /**
     * 
     * @param x int整型 
     * @return int整型
     */
    int sqrt(int x) {
        // write code here
        if(x<=0)return 0;
        for(int i=1;i<=x;i++)
        {
            if(i*i<=x&&(i+1)*(i+1)>x)return i;
        }
    }
};
posted @ 2020-11-08 22:49  回归梦想  阅读(119)  评论(0编辑  收藏  举报