题解 | #求平方根#
求平方根
http://www.nowcoder.com/practice/09fbfb16140b40499951f55113f2166c
暴力
时间复杂度:
class Solution {
public:
/**
*
* @param x int整型
* @return int整型
*/
int sqrt(int x) {
// write code here
long i = 0;
for(; i * i <= x; i ++);
return i * i > x ? i - 1: i;
}
}; 二分
时间复杂度:
class Solution {
public:
/**
*
* @param x int整型
* @return int整型
*/
int sqrt(int x) {
// write code here
long left = 0, right = x;
while(left < right){
long mid = left + (right - left) / 2;
if(mid * mid >= x) right = mid;
else left = mid + 1;
}
return left * left > x ? left - 1 : left;
}
};
阿里云成长空间 743人发布