Newton method, need enought accuracy of tolerance to handle edge case INT_MAX and INT_MIN:

 1 class Solution {
 2 public:
 3     int sqrt(int x) {
 4         double first = x, second = 0;
 5         while (fabs(first - second) > 0.0000001) {
 6             second = first;
 7             first = (second + x/second)/2;
 8         }
 9         return int(first);
10     }
11 };

 

Binary search, please remember check 0 and 1 for corner case:

 1 class Solution {
 2 public:
 3     int sqrt(int x) {
 4         if (x < 2) return x;
 5         int start = 0, end = x, mid = 0;
 6         while (end - start > 1) {
 7             mid = (end + start)/2;
 8             if (mid > 46340) end = mid;
 9             else if (mid*mid <= x) start = mid;
10             else end = mid;
11         }
12         return start;
13     }
14 };

 

posted on 2015-03-24 14:46  keepshuatishuati  阅读(131)  评论(0编辑  收藏  举报