Implement int sqrt(int x)
.
Compute and return the square root of x.
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
mid*mid 以及 (mid + 1) * (mid + 1)都有可能溢出,所以要使用long类型。
class Solution { /** * @param x: An integer * @return: The sqrt of x */ public int sqrt(int x) { // write your code here if(x <= 1) return x; long left = 1; long right = x / 2; while(left < right){ long mid = left + (right - left) / 2; if((mid * mid) <= x && ((mid + 1) * (mid + 1)) > x) return (int)mid; else if(((mid + 1) * (mid + 1)) <= x) left = mid + 1; else right = mid - 1; } return (int)left; } }