69. Sqrt(x)

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
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.
这里写图片描述
实现一个sqrt函数。

2,题目思路
可以直接用遍历的办法来实现这样的sqrt函数,需要注意的是存储平方的值为long。
方法二也是遍历,不过检索的空间缩小了很多,因此速度也很快。

3,程序源码
方法1
关于ios::sync_with_stdio(false);和 cin.tie(0)加速c++输入输出流

static vector<string> strs = [](){
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    return vector<string>{};
}();
//加了上面一段代码,速度直接从42ms下降到了28ms,很神奇!
//在C++类的输入输出中,cin和cout效率比较低,而造成额外的时间消耗
//cin,cout之所以效率低,是因为先把要输出的东西存入缓冲区,再输出,导致效率降低,而这段语句可以来打消iostream的输入 输出缓存,可以节省许多时间,使效率与scanf与printf相差无几,还有应注意的是scanf与printf使用的头文件应是stdio.h而不是 iostream。

class Solution {
public:
    int mySqrt(int x) {
        long long s = 0, i =0;
        while(s<=x){
            i++;
            s = i*i;
        }
        return i-1;
    }
};

方法2:

static vector<string> strs = [](){
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    return vector<string>{};
}(); 

class Solution {
public:
    int mySqrt(int x) {
        long r = x;
        long a = x;
        while(r * r > a) {
            r = (r + a / r) / 2;
        }
        return r;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值