LeetCode:Sqrt(x)

问题描述:

Implement int sqrt(int x).

Compute and return the square root of x.

1、开始我想到的是二分法,但是貌似二分法还是超时了。

class Solution {

public:
   int mySqrt(int x)
    {
       int low = 1;
       int high = x;
       int mid = (1 + x) / 2;
       for(int i = mid; i < x; ++i)
       {
           if(i * i == x)
           {
                return i;
           }
           else if(i * i > x )
                 {
                  mid = (mid + low) / 2;
                 }
                 else
                 {
                     mid = (mid + high) / 2;
                 }
       }
       return 0;
    }
};
2、紧接着我想到了牛顿迭代法,最后尝试了好久,终于通过

class Solution {
public:
   int mySqrt(int x)
    {
       if(x == 0)
        return 0;
       double pre = 0;
       double cur = 1;
       do
       {
           pre = cur;
           cur = x / (2 *pre) + pre / 2.0;
       }while (abs(cur - pre) > 0.00001); 
       return int(pre);
    }
};


你可能感兴趣的:(LeetCode,C++)