题解 | #求平方根#
求平方根
http://www.nowcoder.com/practice/09fbfb16140b40499951f55113f2166c
算法题目中也提示了,就是用二分法求平方根。唯一需要注意的一点是防止加法和乘法的溢出。最简单的办法就是用 long 接收。这里将其改为除法
算法比较简单。运行时间 2ms 。内存 242 KB
class Solution {
public:
/**
*
* @param x int整型
* @return int整型
*/
int sqrt(int x) {
// write code here
if(!x) return 0;
int i = 0;
int j = x;
int s = (float)i/2 + (float)j/2;
if(!s) s = 1;
while(!(s<=x/s && (s+1)>x/(s+1))){
if(s<x/s) i = s + 1;
if(s>x/s) j = s - 1;
s = (float)i/2 + (float)j/2;
if(!s) s = 1;
}
return s;
}
};
查看3道真题和解析
