标签:
Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:binary search ,柯西不等式 √ab<=(a+b)/2;
注意:overflow问题。新技巧:如果是乘法引起的overflow,可以试试改成除法。!!so clever!
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; } };
标签:
原文地址:http://www.cnblogs.com/renrenbinbin/p/4333868.html