Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
Code:
class Solution { public: int sqrt(int x) { int start=0; int end=x/2>std::sqrt(INT_MAX)?std::sqrt(INT_MAX):x/2+1; while(start<=end){ int mid=(start+end)/2; if(x==mid*mid) return mid; else if(mid*mid<x) start=mid+1; else end=mid-1; } return (start+end)/2; } };
Analysis:
According to Newton's Method(http://en.wikipedia.org/wiki/Newton's_method), we can use
to get the sqrt(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==1) {return 1;} double x0 = 1; double x1; while (true){ x1 = (x0+ x/x0)/2; if (abs(x1-x0)<1){return x1;} x0=x1; } } };