ZhangZhihui's Blog  

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

 

Example 1:

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.

 

Constraints:

  • 0 <= x <= 231 - 1

 

My Solution:

class Solution:
    def mySqrt(self, x: int) -> int:
        if x == 0:
            return 0
        
        i = 0
        y = x
        while y // 100 > 0:
            y = y // 100
            i += 1
        range_from = 10 ** i

        for i in range(range_from, x + 1):
            if i * i == x:
                return i
            elif i * i > x:
                return i - 1

 

 

ChatGPT's Solution:

class Solution:
    def mySqrt(self, x: int) -> int:
        if x < 2:
            return x
        
        left, right = 1, x // 2

        while left <= right:
            mid = (left + right) // 2
            if mid * mid == x:
                return mid
            elif mid * mid < x:
                left = mid + 1
            else:
                right = mid - 1
        
        return right  # right is the floor of sqrt(x)

 

 

posted on 2025-04-05 18:13  ZhangZhihuiAAA  阅读(17)  评论(0)    收藏  举报