http://www.lintcode.com/en/problem/sqrtx/

Implement int sqrt(int x).

Compute and return the square root of x.

Example sqrt(3) = 1 sqrt(4) = 2 sqrt(5) = 2 sqrt(10) = 3

解题:这题让我们implement一个开根方法,也可以用二分法来找一个值,检查部分就是那个值的平方小于等于x,我们就更新start = mid。

public class Solution {
    /*
     * @param x: An integer
     * @return: The sqrt of x
     */
    public int sqrt(int x) {
        // write your code here
        long start = 1, end = x;

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

        if (end * end <= x) {
            return (int) end;
        }
        return (int) start;
    }
}

results matching ""

    No results matching ""