[leetcode] 69. Sqrt(x) 解题报告

题目链接:https://leetcode.com/problems/sqrtx/

Implement int sqrt(int x).

Compute and return the square root of x.


思路:二分查找,每次看中间的数平方是不是和当前数相等.

代码如下:

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


你可能感兴趣的:(Math,LeetCode,Facebook)