題目
https://leetcode-cn.com/problems/sqrtx/
思路
使i從1開始查找,判斷i*i > x時,循環結束,當i*i<=x,記錄res的值,這整個過程,可以用二分查找的思想我直接暴力😭😭,思維還不夠敏捷。
AC代碼
class Solution {
public:
int mySqrt(int x) {
/*
long long res;
if (x == 0) return 0;
if(x == 1) return 1;
long long i = 1;
while (i*i <= x){
res = i;
i++;
}
return res;
*/
//二分法
int left = 0;
int right = x;
int res;
if (x == 0) return 0;
if (x == 1) return 1;
while (left <= right){
int mid = (right - left) / 2 + left; //防止溢出
if ((long long) mid*mid <= x){
res = mid;
left = mid+1;
}
else
right = mid-1;
}
return res; //對從1~n遍歷查找想要的值,應該使用二分查找
}
};