mySqrt.py 522 B

12345678910111213141516171819202122232425
  1. def mySqrt(x: int) -> int:
  2. # if x == 0:
  3. # return 0
  4. # if x == 1:
  5. # return 1
  6. # i = 0
  7. # while i <= x//2:
  8. # if (i+1) * (i+1) > x and i * i <= x:
  9. # return i
  10. # elif (i+1) * (i+1) == x:
  11. # return i + 1
  12. # else:
  13. # i += 1
  14. l, r, ans = 0, x, -1
  15. while l <= r:
  16. mid = l + (r - l) // 2
  17. if mid * mid <= x:
  18. ans = mid
  19. l = mid + 1
  20. else:
  21. r = mid - 1
  22. return ans
  23. print(mySqrt(10))