Implement int sqrt(int x)
.
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4 Output: 2
Example 2:
Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
题目链接:https://leetcode.com/problems/sqrtx/
自己写了一份代码,然后看别人,这tm代码都能过,不超时????耍流氓啊
class Solution {
public:
int mySqrt(int x) {
long start=0,end=x/2,mid=0;
while(start<=end)
{
mid=(start+end)/2;
if(mid*mid==x)
{
return mid;
}
else if(mid*mid<x)
{
start=mid+1;
}
else
{
end=mid-1;
}
}
return start*start>x?start-1:start;
}
};
看看人家耍流氓的代码!!!!
class Solution {
public:
int mySqrt(int x) {
int i=0;
for(;i<=46340;++i)
if(i*i>x)return i-1;
else if(i*i==x)return i;
return i-1;
}
};
这都能过,出这题还有意思吗?????