题意:

image.png

解题思路:

  1. 思路:
  2. 二分出最大的 k,满足$k^2$ < x

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer $x
  4. * @return Integer
  5. */
  6. function mySqrt($x) {
  7. if ($x == 0 || $x == 1) return $x;
  8. $low = 1; $high = $x;
  9. while ($low <= $high) {
  10. $mid = $low + floor(($high - $low) >> 1);
  11. if ($mid == floor($x / $mid)) {
  12. return $mid;
  13. } else if ($mid > floor($x / $mid)) {
  14. $high = $mid - 1;
  15. } else {
  16. $low = $mid + 1;
  17. $res = $mid;
  18. }
  19. }
  20. return $res;
  21. }
  22. }

GO代码实现:

  1. func mySqrt(x int) int {
  2. left, right := 0, x
  3. for left <= right {
  4. mid := left + (right - left) >> 1
  5. if mid * mid <= x {
  6. left = mid + 1
  7. } else {
  8. right = mid - 1
  9. }
  10. }
  11. return left - 1
  12. }