code the reverse integers problem from leetcode
- User
code the reverse integers problem from leetcode
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_numThe algorithm works by:
- Extracting and storing the sign of the input number
- Working with the absolute value to simplify digit extraction
- Using modulo 10 to get the last digit and integer division to remove it
- Building the reversed number by multiplying by 10 and adding each digit
- Checking for overflow before each operation to prevent issues
- Applying the original sign back to the result
- 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
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.