Tuesday, March 7, 2017

[LintCode] 141 Sqrt(x) 解题报告

Description
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


Challenge
O(log(x))

思路
二分法。注意 x * x可能会越界,所以要用long

Code
class Solution {
    /**
     * @param x: An integer
     * @return: The sqrt of x
     */
    public int sqrt(int x) {
        // write your code here

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