Lastnumber that number^2 <= x

class Solution {
public:
    /**
     * @param x: An integer
     * @return: The sqrt of x
     */
    int sqrt(int x) {
        if (x == 0) {
            return 0;
        }

        long int start = 1;
        long int end = x;

        while (start + 1 < end) {
            long int mid = (end - start) / 2 + start;
            long int square = mid * mid;
            if (square == x) {
                return mid;
            } else if (square < x) {
                start = mid;
            } else if (square > x) {
                end = mid;
            }
        }
        if (end * end <= x) {
            return end;
        }
        return start;
    }
};

results matching ""

    No results matching ""