Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:binary search ,柯西不等式 √ab<=(a+b)/2;
注意:overflow问题。新技巧:如果是乘法引起的overflow,可以试试改成除法。!!so clever!
另一种方法是用 位移运算。十分巧妙。原理在《位移运算》一章讲解 http://www.cnblogs.com/renrenbinbin/p/4337552.html
class Solution { public: /*overflow must be considered*/ int sqrt(int x) { int a=1; int b=x; int mid=0; while(a<b){ mid=(a+b)/2; if(mid>x/mid) b=mid-1; else a=mid+1; } if(a*a>x) return a-1; else return b; } };
方法2
class Solution { public: /*overflow must be considered*/ int sqrt(int x) { if(x==0) return 0; int a=1; int n=0; while((a<<n)<=(x/(a<<n))){ n++; } n--; int rel = a<<n; int b=n-1; while(b>=0){ int m=1<<b; if((rel|m)<=x/(rel|m)){ rel|=m; } b--; } return rel; } };