Sqrt(x) — Right Boundary Binary Search
Advertisement
Problem 305 · Sqrt(x)
Difficulty: Easy · Pattern: Right Boundary
Return the integer square root (floor).
Solutions
# Python
def mySqrt(x):
lo, hi = 0, x
while lo < hi:
mid = lo + (hi-lo+1)//2 # upper mid
if mid*mid <= x: lo = mid # could be answer
else: hi = mid-1
return lo
// Java
public int mySqrt(int x) {
long lo=0, hi=x;
while (lo<hi) {
long mid=lo+(hi-lo+1)/2;
if (mid*mid<=x) lo=mid; else hi=mid-1;
}
return (int)lo;
}
// C++
int mySqrt(int x) {
long lo=0, hi=x;
while (lo<hi) { long mid=lo+(hi-lo+1)/2; if(mid*mid<=x) lo=mid; else hi=mid-1; }
return lo;
}
Complexity
- Time: O(log x)
- Space: O(1)
Advertisement