[LeetCode] Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

 

Hide Tags
 Math Binary Search
 
思路:整体上用2分比逐个比较强。
 
首先,给出一个错误的版本:错误之处在于红色部分,当mid较大时,mid*mid会超过INT_MAX溢出。
        int sqrt(int x) {
            int low = 0;
            int high = x;
            int mid = 0;;

            while(low <= high)
            {
                mid = (high - low)/2 + low;
                cout << "low\t" << low << endl;
                cout << "high\t" << high<< endl;
                cout << "mid\t" << mid<< endl;
                if(x == INT_MAX)
                    break;
                if( (mid * mid) <= x && (mid+1) * (mid+1) > x)
                    return mid;
                else if(mid * mid < x )
                {
                   low = mid + 1; 
                }
                else
                {
                   high = mid - 1; 
                }
            }

            return mid;
        }

然后给出一个AC版本,用mid<x/mid 来代替,同时由于有除法,要保证mid不等于0,当x==1时,mid就会为0,所以特殊处理,当x》=2时,mid》=1,就没问题了。

class Solution {
    public:
        int sqrt(int x) {
            int low = 0;
            int high = x;
            int mid = 0;;

            if(x == 0) return 0;
            if(x < 0) return -1;
            if(x == 1) return 1;

            while(low <= high)
            {
                mid = (high - low)/2 + low;
                #if 0
                cout << "low\t" << low << endl;
                cout << "high\t" << high<< endl;
                cout << "mid\t" << mid<< endl;
                #endif
                if( mid  <= x/mid && (mid+1) > x/(mid+1))
                    return mid;
                else if( mid < x/mid )
                {
                   low = mid + 1;
                }
                else
                {
                   high = mid - 1;
                }
            }

            return -1;
        }  
};

 

 

 
 
posted @ 2015-03-10 11:35  穆穆兔兔  阅读(141)  评论(0编辑  收藏  举报