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))
halfhalf二分法。思想一样,就是取mid后判断的是mid*mid和x的关系。注意用long类型避免乘法溢出。
public class Solution { /* * @param x: An integer * @return: The sqrt of x */ public int sqrt(int x) { // write your code here if (x < 0){ throw new IllegalArgumentException(); } long start = 0; long end = x; while (start + 1 < end){ long mid = start + (end - start) / 2; long mult = mid * mid; if (x < mult){ end = mid; } else if (x == mult){ return (int)mid; } else { start = mid; } } if (end * end == x){ return (int)end; } return (int)start; } }