[Leetcode]Sqrt(x)

Sqrt(x)
Total Accepted: 74812 Total Submissions: 310770 Difficulty: Medium

Implement int sqrt(int x).

Compute and return the square root of x.

Subscribe to see which companies asked this question

题目很简单,弄清题意。使用二分查找即可,有一点:输入不一定是个完全平方数,如果不是的话取根的下边界整数。

class Solution {
public:
    int mySqrt(int x) {
        if(x <= 0)  return 0;
        int l = 1,r = x;
        int mid;
        while(l <= r){
            mid = l + ((r - l) / 2);
            if(mid  > x / mid){
                r = mid - 1;
            }
            else if(mid < x / mid){
                l = mid + 1;
            }
            else{
                return mid;
            }
        }
        return r;
    }
};

posted on 2015-12-02 19:31  泉山绿树  阅读(28)  评论(0)    收藏  举报

导航