69. Sqrt(x)

Descr
class Solution {
public:
    int mySqrt(int x) {
        if(x==0)
			return 0;
		int mid;
		int start=1,end=min(x/2,46340);
		while(start=mid x/(mid+1)=mid+1)
				start=mid+1;
		}
		return start;
    }
};

iption Hints Submissions Discuss Solution
Discuss Pick One

Implement int sqrt(int x).

Compute and return the square root of x.


Seen this question in a real interview before?    
Yes
 
计算并返回x的平方根
使用for循环当然可以,但是二分法可以快速的解决
代码:
class Solution {
public:
    int mySqrt(int x) {
        if(x==0)
			return 0;
		int mid;
		int start=1,end=min(x/2,46340);
		while(start=mid x/(mid+1)=mid+1)
				start=mid+1;
		}
		return start;
    }
};


你可能感兴趣的:(Binary,search)