leetcode 53: Sqrt(x)
Sqrt(x)Apr
3 '12
Implement int
sqrt(int x).
Compute and return the square root of x.
class Solution {
public:
int sqrt(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// Start typing your Java solution below
// DO NOT write main() function
if( x <=0 ) return 0;
unsigned k = (1<< (sizeof(x)*8 -1)/2 );
int rel = 0;
while( k>0) {
rel |= k;
unsigned t = rel*rel;
cout<<'$'<<t<<'$';
if( t > x) {
rel -= k;
}
k >>= 1;
}
return rel;
}
};
浙公网安备 33010602011771号