Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

C++:
01 class Solution {
02 public:
03     int sqrt(int x) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         if(x==0)
07             return 0;
08         if(x<4)
09             return 1;
10         int t=2;
11         while(true)
12         {
13             int tmp=x/t;
14             if(t==tmp)
15                 return t;
16             if(tmp==t+1)
17                 return t;
18             if(tmp==t1)
19                 return tmp;
20             t=(t+tmp)/2;
21         }
22     }
23 };
Advertisements
This entry was posted in Number trick. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s