LeetCode-Sqrt(x)
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
if(x<=0)return 0;
if(x<4)return 1;
else if(x==4)return 2;
else{
int start=1,end=46340;
if(end*end<=x)return end;
while(start<=end){
int mid=(start+end)/2;
int a=mid*mid;
if(a>x){
end=mid-1;
}
else{
if(a+mid*2+1>x)return mid;
start=mid+1;
}
}
}
}
};
牛顿迭代法
class Solution {
public:
int sqrt(int x) {
if(x<1)return 0;
unsigned long x1 = x - 1;
unsigned s = 1;
unsigned g0,g1;
/* 初值设定 */
if (x1 > 65535) {s += 8; x1 >>= 16;}
if (x1 > 255) {s += 4; x1 >>= 8;}
if (x1 > 15) {s += 2; x1 >>= 4;}
if (x1 > 3) {s += 1; x1 >>= 2;}
/*迭代*/
g0 = 1 << s;
g1 = (g0 + (x >> s)) >> 1;
while(g1 < g0)
{
g0 = g1;
g1 = (g0 + x/g0) >> 1;
}
return g0;
}
};
参见
http://www.cnblogs.com/Matrix_Yao/archive/2009/07/28/1532883.html
浙公网安备 33010602011771号