Close Menu

    Maximum Consecutive Ones | Leetcode 485 | Explained with Images

    March 24, 2025

    Find missing number in an array | Leetcode 268 | Explained

    March 14, 2025

    Union of 2 Sorted Arrays with Duplicates | Explained with Images

    March 13, 2025

    Linear Search in Python | Explained with Images and Examples

    March 10, 2025
    Facebook X (Twitter) Instagram
    Facebook X (Twitter) Instagram Pinterest Vimeo
    Code and Debug AcademyCode and Debug Academy
    Subscribe
    Code and Debug AcademyCode and Debug Academy
    Home»Training»Leetcode #7 : Reverse Integer Python Program Explained
    Training

    Leetcode #7 : Reverse Integer Python Program Explained

    Code and DebugBy Code and DebugDecember 24, 2024No Comments4 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Reverse Integer Python Program
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Hi everyone! In this article, we’ll guide you through a detailed explanation of the Reverse Integer Python Program [Problem Link].

    Examples:

    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

    1.Optimal Solution [Reverse Integer Python Program]

    Problem Statement:

    Objective: The code aims to solve the problem of reversing the digits of a 32-bit signed integer “x”.

    Purpose: The function reverse is designed to take an integer “x”, reverse its digits, and return the reversed integer. If the reversed integer overflows beyond the 32-bit signed integer range, it returns 0.

    Expected Input and Output:

    • Input: A 32-bit signed integer “x”.
    • Output: The reversed integer or 0 if the result overflows.

    Also learn Python Program to Count Number of Digits.

    Intuition and Approach:

    Intuition: To reverse the digits of an integer, we can repeatedly extract the last digit and build the reversed number step by step. If the original number is negative, we handle the sign separately.

    Approach:

    1. Check if the number is negative and store this information
    2. Convert the number to its absolute value for easier processing
    3. Initialize a variable to store the reversed number
    4. Use a loop to extract the last digit of the number and append it to the reversed number
    5. Ensure the result does not overflow the 32-bit signed integer range
    6. Restore the sign if the original number was negative
    7. Return the reversed number or 0 if it overflows

    Code:

    class Solution:
        def reverse(self, x: int) -> int:
            is_negative = False
            if x < 0:
                is_negative = True
            num = abs(x)
            answer = 0
            while num > 0:
                last_digit = num % 10
                answer = (answer * 10) + last_digit
                num //= 10
    
            if answer < (-(21**31)) or answer > (2**31 - 1):
                return 0
            return -answer if is_negative else answer
    1. Check for Negativity: A boolean variable is_negative is set to True if “x” is negative
    2. Absolute Value: The absolute value of “x” is stored in “num” for easier manipulation
    3. Initialize Answer: An integer answer is initialized to 0 to build the reversed number
    4. Loop to Reverse Digits:
      1. While “num” is greater than 0, the last digit is extracted using num % 10
      2. This digit is appended to answer by multiplying answer by 10 and adding the digit
      3. The last digit is removed from “num” using integer division by 10
    5. Overflow Check: After the loop, check if the reversed number is within the 32-bit signed integer range. If not, return 0.
    6. Restore Sign: If the original number was negative, return the negated result. Otherwise, return the result.

    Dry Run:

    Let’s walk you through a step-by-step execution with a sample input

    Dry Run [Optimal Solution]

    Potential Edge Cases:

    1. Zero Input:
      • If x = 0, the function should return 0
    2. Negative Numbers:
      • For x = -123, the function should return -321
    3. Overflow:
      • If reversing the number causes it to exceed the 32-bit signed integer range, the function should return 0.
      • Examples: x = 1534236469 should return 0 because the reversed number 9646324351 exceeds the 32-bit limit.

    Time and Space Complexity:

    Time Complexity: The time complexity is O(log10​ . N), where n is the absolute value of the input number. This is because the number of iterations in the loop is proportional to the number of digits in the number.

    Space Complexity: The space complexity is O(1). The function uses a fixed amount of space regardless of the input size.


    For any changes to the document, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Code and Debug
    • Website

    Related Posts

    Training

    Best Data Analytics Training in Kochi for Clearing Placements

    February 26, 2025
    Training

    Best Data Analytics Course in Noida using Python

    February 25, 2025
    Training

    Best Data Analytics Training in Surat for Placement Interviews

    February 18, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Facebook X (Twitter) Instagram Pinterest
    © 2025 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.