题目描述:
Implement int sqrt(int x).
Compute and return the square root of x.
Hide Tags Math Binary Search
分析:类型都是整型,直接二分
Implement int sqrt(int x).
Compute and return the square root of x.
Hide Tags Math Binary Search
分析:类型都是整型,直接二分
但是要注意处理非完全平方数。
/**///8ms//*/
class Solution {
public:
int mySqrt(int x) {
if(x == 0)
return 0;
unsigned long long b = 0;
unsigned long long e = x/2+1;
unsigned long long mid = 0;
unsigned long long tmp = 0;
while(b < e){
mid = (b + e) / 2;
tmp = mid * mid;
if(tmp == x){
return mid;
}
else if (tmp < x)
b = mid + 1;
else e = mid- 1;
}
if(x < e * e) //判断最后的最大边界,如果它的平方
return e - 1;
else return e;
}
};