Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514· AnthropicHugging Face LMArena Human Preference 140K

code the reverse integers problem from leetcode

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.0-flash-001’s answer.
  1. User

    code the reverse integers problem from leetcode

  2. Claude Assistant

    Here's a solution for the reverse integer problem:

    def reverse(x: int) -> int:
        # Handle the sign
        sign = -1 if x < 0 else 1
        x = abs(x)
        
        # Reverse the digits
        reversed_num = 0
        while x != 0:
            digit = x % 10
            x //= 10
            
            # Check for overflow before adding the digit
            if reversed_num > (2**31 - 1 - digit) // 10:
                return 0
                
            reversed_num = reversed_num * 10 + digit
        
        # Apply the sign
        reversed_num *= sign
        
        # Check if the result is within 32-bit signed integer range
        if reversed_num < -2**31 or reversed_num > 2**31 - 1:
            return 0
            
        return reversed_num
    

    The algorithm works by:

    1. Extracting and storing the sign of the input number
    2. Working with the absolute value to simplify digit extraction
    3. Using modulo 10 to get the last digit and integer division to remove it
    4. Building the reversed number by multiplying by 10 and adding each digit
    5. Checking for overflow before each operation to prevent issues
    6. Applying the original sign back to the result
    7. Ensuring the final result fits within a 32-bit signed integer range [-2³¹, 2³¹-1]

    Time complexity: O(log n) where n is the input number (number of digits) Space complexity: O(1) - only using a constant amount of extra space

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.