square root binary search in leetcode69.x

  • https://leetcode.cn/problems/sqrtx/

  • Given a non-negative integer x, compute and return the arithmetic square root of x.

  • Since the return type is an integer, only the integer part of the result is kept, and the decimal part will be discarded.

  • Note: Any built-in exponential functions and operators such as pow(x, 0.5) or x ** 0.5 are not allowed.

示例 1:

输入:x = 4
输出:2
示例 2:

输入:x = 8
输出:2
解释:8 的算术平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
提示:
0 <= x <= 2^31 - 1
class Solution {
    
    
public:
    int mySqrt(int x) {
    
    

        if(x<=1){
    
    return x;}
        long long r=x;// long long 类型 int 当 x = 2147483647 会报错
        while(r>x/r){
    
    
            r = (r+x/r)/2 ;// 基本不等式(a+b)/2 >=√ab 推导自 (a-b)^2 >= 0,注意 a>0 且 b>0
        }
        return int(r);
    }
};

Guess you like

Origin blog.csdn.net/ResumeProject/article/details/132164471