Description

Implement int sqrt(int x).

Compute and return the square root of x.

思路

  • 二分查找

代码

class Solution {
public:
   int mySqrt(int x) {
		if (x < 0) return INT_MIN;
		if (x <= 1) return x;
		
		int low = 1, high = x, mid = 0, res = 1;
		while(low <= high){
		    mid = low + (high - low) / 2;
		    if(mid <= x / mid){
		        low = mid + 1;
		        res = mid;
		    }
		    else high = mid - 1;
		}
		
    	return res;
	}
	
};

相关文章:

  • 2021-11-09
  • 2021-06-14
  • 2022-01-22
  • 2021-07-07
  • 2022-12-23
  • 2021-11-29
猜你喜欢
  • 2021-11-23
  • 2021-10-07
  • 2021-12-08
  • 2021-08-08
相关资源
相似解决方案