69. Sqrt(x)
Asked at 16Bloomberg62Amazon59Google52Apple51Meta49Microsoft49Grammarly83Zoho81TikTok65Citadel64tcs50Adobe44LinkedIn43Goldman Sachs42Oracle35Uber30
Problem
Return ⌊√x⌋ for a non-negative integer x, without any built-in power or square-root function.
Example: 4 → 2; 8 → 2
Constraints: x ≤ 2³¹ − 1.
Largest m with m*m ≤ x. Search for the first m with m*m > x, answer m − 1.
Complexity: O(log x).
class Solution:
def mySqrt(self, x: int) -> int:
lo, hi = 0, x + 1 # first m with m*m > x
while lo < hi:
m = (lo + hi) // 2
if m * m > x:
hi = m
else:
lo = m + 1
return lo - 1
assert Solution().mySqrt(4) == 2
assert Solution().mySqrt(8) == 2
assert Solution().mySqrt(0) == 0
class Solution {
public int mySqrt(int x) {
long lo = 0, hi = (long) x + 1;
while (lo < hi) {
long m = (lo + hi) / 2;
if (m * m > x) hi = m; else lo = m + 1;
}
return (int) (lo - 1);
}
}
func mySqrt(x int) int {
lo, hi := 0, x+1 // first m with m*m > x
for lo < hi {
m := lo + (hi-lo)/2
if m*m > x {
hi = m
} else {
lo = m + 1
}
}
return lo - 1
}