码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Sqrt(x)

时间:2015-03-10 13:35:22      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

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;
        }  
};

 

 

 
 

[LeetCode] Sqrt(x)

标签:

原文地址:http://www.cnblogs.com/diegodu/p/4325528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!