Leetcode -- Sqrt(x)
题目:
Implement int sqrt(int x)
.
Compute and return the square root of x
思路:1、利用二分法查找
2、Discuss里面贴了一些利用移位做的方法;
BTW: C++11定义的Sqrt函数 from <cmath>
double sqrt (double x); float sqrt (float x); long double sqrt (long double x); double sqrt (T x); // additional overloads for integral types
CODE:
int sqrt(int x) {
if(x<=1) { return x; }
int left = 1;
int right = x;
while(left<=right) {
int mid = left + ((right-left)>>1);
if(mid == x/mid) {
return mid;
}
else if(mid < x/mid) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return right;
}
using bit manipulation:
public int sqrt(int x) {
long long ans = 0;
long long bit = 1l << 16; //输入为int,这里必须为long long
while(bit > 0) {
ans |= bit;
if (ans * ans > x) {
ans ^= bit;
}else iff(ans * ans == x){
break;
}
bit >>= 1;
}
return (int)ans;
}