Solving Leetcode Interviews in Seconds with AI: Reverse Integer
Introduction
In this blog post, we will explore how to solve the LeetCode problem "7" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Constraints: -231 <= x <= 231 - 1
Explanation
Here's the approach to solve this problem efficiently:
- Iterative Reversal: Extract digits from the input integer one by one using the modulo operator (
%). Build the reversed integer by repeatedly multiplying the current reversed value by 10 and adding the extracted digit. - Overflow Check: Crucially, check for potential overflow before updating the reversed integer in each iteration. This avoids the need to store a 64-bit integer and adheres to the problem constraints. The overflow check looks at the next potential value of the reversed integer and determines if it will exceed the maximum or minimum 32-bit integer value.
Sign Handling: Preserve the sign of the original integer.
Runtime Complexity: O(log|x|), where x is the input integer (number of digits). Storage Complexity: O(1).
Code
def reverse(x: int) -> int:
"""
Reverses the digits of a 32-bit signed integer.
Args:
x: The integer to reverse.
Returns:
The reversed integer, or 0 if the reversed value overflows.
"""
MIN_INT = -2**31
MAX_INT = 2**31 - 1
reversed_x = 0
sign = -1 if x < 0 else 1
x = abs(x)
while x > 0:
digit = x % 10
# Overflow check BEFORE updating reversed_x
if reversed_x > MAX_INT // 10 or (reversed_x == MAX_INT // 10 and digit > MAX_INT % 10):
return 0
if reversed_x < MIN_INT // 10 or (reversed_x == MIN_INT // 10 and digit < MIN_INT % -10):
return 0
reversed_x = reversed_x * 10 + digit
x //= 10
return sign * reversed_x