Implement int sqrt(int x)
.
Compute and return the square root of x.
1.
class Solution { public: int mySqrt(int x) { if(x == 0 || x == 1) return x; int l=1, r=x/2+1, m; while(l<=r) { m = (l+r)>>1; long long mul = (long long)m*(long long)m; if(mul > x) r = m-1; else if(mul < x) l = m+1; else return m; } return r; } };
注意:
long long mul = (long long)m*(long long)m;
这一句中,要先将m转换为long long型,再相乘。
2. Newton's Method
// http://en.wikipedia.org/wiki/Newton%27s_method int sqrt_nt(int x) { if (x == 0) return 0; double last = 0; double res = 1; while (res != last) { last = res; res = (res + x / res) / 2; } return int(res); }