[LeetCode]--69. Sqrt(x)

    xiaoxiao2025-11-07  20

    Implement int sqrt(int x).

    Compute and return the square root of x.

    我采用的是二分法。每次折中求平方,如果大了就把中值赋给大的,如果小了就把中值赋给小的。

    public int mySqrt(int x) { 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; }
    最新回复(0)