您的位置:首页 > 其它

leetcode 53: Sqrt(x)

2013-01-26 05:25 375 查看
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;
}
};


public class Solution {

//-1, 0, 1, 9, 11, MAX_INT, MIN_INT
public int sqrt(int x) {
// Start typing your Java solution below
// DO NOT write main() function
if(x<0) return -1;
int res = 0;
int k = 1<<15;  // can only shift 15 bits. if shift 16, will be overflow.

while(k>0) {
res |= k;
if( res * res > x) {
res -= k;
}
k >>= 1;
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: