PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python » Programs and Examples » Python Programs to Reverse an Integer Number

Python Programs to Reverse an Integer Number

Updated on: March 31, 2025 | Leave a Comment

This article discussed several ways to reverse an integer number in Python. It is helpful to check if the number is a palindrome.

Let’s discuss each of them in detail with examples using Python.

Table of contents

  • 1. How to reverse an integer number in Python
  • 2. Using a Mathematical Approach
  • 3. Using Recursion
  • 4. Using List Reversal
  • Summary

1. How to reverse an integer number in Python

Below are the steps to reverse an integer number using string slicing in Python.

  1. Get Input

    Accept an integer number from a user using the input() function.

  2. Conversion

    Converts the integer number into a string using str() function . For Example, str(1234) = "1234"

  3. Reverse the String Using Slicing

    The slicing syntax [::-1] is a powerful way to reverse a string in Python. For Example, "1234"[::-1] = "4321"

  4. Handle Negative Numbers

    Here, we remove the last character of the reversed string, which is the ‘-‘ sign, and place it in front of the reversed string.
    For Example, n = -5678. reversed_str = "8765-"
    res = '-' + reversed_str[:-1] = it removes the last character ('-') and ensures the '-' is placed at the front

  5. Convert Back to Integer

    Converts the reversed string back to an integer using int() function. For Example, int("4321") = 4321

Code Example

num = 123456
# Convert the integer to string and reverse it using slicing
reversed_str = str(num)[::-1]

# Handle negative numbers
if num < 0:
    reversed_int = int('-' + reversed_str[:-1])  # Exclude the last character which is '-'
else:
    reversed_int = int(reversed_str)

print('Reversed Integer:', reversed_int)Code language: Python (python)

Output:

Reversed Integer: 654321Code language: Python (python)

2. Using a Mathematical Approach

The mathematical approach to reversing an integer involves extracting each digit from the number and building a new reversed number. This method does not rely on converting the number into a string but instead uses modulus (%) and division (//) operations.

Understanding how digits are extracted:
Consider a number 1234. To extract the last digit, we use:

  • Modulus operator (% 10): 1234 % 10 = 4 (Extract the last digit)
  • Floor division (// 10): 1234 // 10 = 123 (Remove the last digit)

Using this approach, we can extract each digit one by one.

Constructing the reversed number:

We initialize a variable reversed_num = 0. To build the reversed number, we follow this pattern:

  • Multiply reversed_num by 10 to shift digits to the left.
  • Add the extracted digit.

Handling Negative Numbers: If the number is negative, we can:

  • Reverse it using the same logic.
  • Restore the negative sign at the end.

For example, let’s reverse 1234:

StepOriginal Number nExtracted Digit (n % 10)reversed_num =(reversed_num * 10 + digit)
1123440 * 10 + 4 = 4
212334 * 10 + 3 = 43
312243 * 10 + 2 = 432
411432 * 10 + 1 = 4321
50 (Done)–Final reversed number:
4321

Code Example

num = 123456
reversed_int = 0
negative = num < 0
num = abs(num)

while num != 0:
    reversed_int = reversed_int * 10 + num % 10 # Extract the last digit and append it to the reversed number
    num //= 10     # Remove the last digit

if negative:
    reversed_int = -reversed_int    # Restore sign if negative

print('Reversed Integer:', reversed_int)

# Output: 
# Reversed Integer: 654321Code language: Python (python)

3. Using Recursion

Recursion is a method where a function calls itself to break down a problem into smaller subproblems. To reverse an integer recursively, we use the same mathematical formula discussed in the above approach, where we extract digits one by one and construct the reversed number in each recursive call.

Understanding the Recursive Approach:

To reverse a number n, we need to:

  1. Extract the last digit (n % 10).
  2. Reduce the number (n // 10).
  3. Accumulate the extracted digits in reverse order.

For example, reversing 1234 using recursion follows this pattern:

StepCurrent nExtracted Digit (n % 10)Remaining Number (n // 10)Partial Result
1123441234
212331243
31221432
4110 (Base Case)4321

The recursion stops when n == 0 (base case).

Code Example

def reverse_int(n, rev=0):
    if n == 0:
        return rev
    else:
        return reverse_int(n // 10, rev * 10 + n % 10)

print('Reversed Integer:', reverse_int(123456))

# Output: 
# Reversed Integer: 654321Code language: Python (python)

4. Using List Reversal

A list reversal approach involves converting the integer into a list of its digits, reversing the order of the list, and then converting it back to an integer. This method utilizes Python’s built-in list manipulation capabilities, such as list() and reverse(), to efficiently reverse the digits.

num = 123456
sign = -1 if num < 0 else 1
n = abs(num)

digits = list(str(num))   # Convert string to list
digits.reverse()      # Reverse the list

reverse_int = sign * int(''.join(digits))   # Convert list to string and then convert string to integer

print('Reversed Integer:', reverse_int)

# Output: 
# Reversed Integer: 654321Code language: Python (python)

Explanation

  • Handle negative number: check if num is negative:
    • If num < 0, sign = -1 (negative number).
    • Otherwise, sign = 1 (positive number).
    • Since num = 123456 (positive), sign = 1.
  • Convert the Number to a List of Characters:
    • str(num) converts 123456 into the string ‘123456’.
    • list(str(num)) converts ‘123456’ into a list: digits = ['1', '2', '3', '4', '5', '6']
  • Reverse the List:
    • The reverse() method reverses the list in place, modifying digits = ['6', '5', '4', '3', '2', '1']
  • Convert the Reversed List Back to an Integer:
    • ''.join(digits) joins the list back into a string: ‘654321’
    • int('654321') converts the string back to an integer: 654321
  • Adjust the sign: Multiply by sign: reverse_int = 1 * 654321. Since sign = 1

Summary

Each of these methods can reverse an integer in Python. The choice of method may depend on your specific needs, such as readability, performance, etc.

  • Using String Slicing ([::-1])
    • Advantage: Simple and concise.
    • Time Complexity: O(d), where d is the number of digits.
    • Space Complexity: O(d), since a new string is created, where d = number of digits
  • Using a Mathematical Approach
    • Advantage: Most efficient approach. No string conversion, reducing memory usage.
    • Time Complexity: O(log n), since each loop iteration removes one digit.
    • Space Complexity: O(1), as no extra storage is needed.
  • Using List Reversal
    • Advantage: Uses Python’s built-in list operations. Easy to understand.
    • Time Complexity: O(d), due to list reversal.
    • Space Complexity: O(d), since the list stores digits.
  • Using Recursion
    • Advantage: A structured and elegant solution.
    • Time Complexity: O(log n), since each recursive call removes one digit.
    • Space Complexity: O(log n), due to the recursive call stack.

Filed Under: Programs and Examples, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Programs and Examples Python Python Basics

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Programs and Examples Python Python Basics
TweetF  sharein  shareP  Pin

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement