Implement int sqrt(int x).

Compute and return the square root of x.

 

 1 class Solution {
 2 public:
 3     int mySqrt(int x) {
 4         unsigned long long begin=0;
 5         unsigned long long end=(x+1)/2;
 6         unsigned long long mid;
 7         unsigned long long tmp;
 8 
 9         while(begin<end)
10         {
11             mid=begin+(end-begin)/2;
12             tmp=mid*mid;
13 
14             if(tmp==x) return mid;
15             else if(tmp<x) begin=mid+1;
16             else end=mid-1;
17         }
18 
19         tmp=end*end;
20 
21         if(tmp>x)
22             return end-1;
23         else
24             return end;
25     }
26 };

 

posted on 2015-05-29 17:20  黄瓜小肥皂  阅读(180)  评论(0编辑  收藏  举报