Compute and return the square root of x.
class Solution {
public:
int sqrt(int x) ;
};
int Solution::sqrt(int x)
{ int i,j;
int output=x;
int value=x;
i=0;
j=x;
if(x==0) return 0;
while(i != j-1)
{int k=(i/2+j/2+(i%2+j%2)/2); //当数很大的时候,i+j就会越界
//cout<<i<<" "<<k<<" "<<j<<endl;
if(k < x/k) //当数很大的时候,k*k就会越界
{
i = k;
if(x/k-k<value/k)
output = k;
}
else if(k > x/k)
{
j = k;
}
else if(k==x/k)
return k;
}
return output;
}
题目并不难,就是要防止大数越界,换一种方式表达