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.

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.

实现int sqrt(int x)。

计算并返回x的平方根,其中x保证为非负整数。

由于返回类型是整数,因此将截断十进制数字,并仅返回结果的整数部分。

2,题目思路

对于这道题,要求实现一个sqrt的函数模型。

在这个函数中,如果可以直接开方,就返回开方的值;如果不能直接开方,就返回取整后的结果。

如果我们直接使用暴力解法,即i*i的进行判断,自然是可以的,但是会造成大量不必要的时间消耗。

因此,一般来说,对于带有逐一便利和搜索的问题,我们一般可以使用二分搜索的思想,来解决这一问题。

需要注意的是,我们不是求正好的开方值,也即是不能以mid == x/mid为结束结果,而是找到小于准确开方值的最大整数。

3,代码实现

int x = []() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution {
public:
    int mySqrt(int x) {
        if(x == 0 || x == 1)
            return x;
        
        int left = 0, right = x;
        int res = -1;
        while(left <= right){
            int mid = left + (right - left)/2;
            if(mid > x/mid)
                right = mid-1;
            else{
                left = mid+1;
                res = mid;  
            }
        }
        return res;
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值