Open In App

Reverse digits of an integer with overflow handled

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
42 Likes
Like
Report

Write a program to reverse an integer assuming that the input is a 32-bit integer. If the reversed integer overflows, print -1 as the output. 

Let us see a simple approach to reverse digits of an integer

C++
C Java Python C# JavaScript PHP

Output
Reverse of no. is 6985

Time Complexity: O(log(num))
Auxiliary Space: O(1)

Optimized Approach:

However, if the number is large such that the reverse overflows, the output is some garbage value. If we run the code above with input as any large number say 1000000045, then the output is some garbage value like 1105032705 or any other garbage value.
How to handle overflow? 
The idea is to store the previous value of the sum can be stored in a variable that can be checked every time to see if the reverse overflowed or not.

Below is the implementation to deal with such a situation.

C++
C Java Python C# JavaScript

Output
Reverse of no. is 54321
WARNING OVERFLOWED!!!
Reverse of no. is 0

Time Complexity: O(log(num))
Auxiliary Space: O(1)

Efficient Approach:

The above approach won't work if we are given a signed 32-bit integer x, and 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. So we cannot multiply the number*10 and then check if the number overflows or not.

We must check the overflow condition before multiplying by 10 by using the following logic :
You are checking the boundary case before you do the operation. (reversed >INT_MAX ) wouldn't work because reversed will overflow and become negative if it goes past MAX_VALUE.  Dividing MAX_VALUE by 10 lets you check the condition without overflowing INT_MAX is equal 2147483647. INT_MIN is equal  -2147483648.  The last digits are 7 and 8. This is the reason why we also  check  rem > 7 and rem < -8 conditions

Implementation:

C++
Java Python C# JavaScript

Output
Reverse of no. is 54321
Reverse of no. is 0

Time Complexity: O(log(num))
Auxiliary Space: O(1)

Approach using slice method:

We convert the integer to a string, reverse the string using the slice operator, and then convert the reversed string back to an integer.

Steps:

  • Convert the integer to a string using the str() function
  • Use the slice operator [::-1] to reverse the string
  • Convert the reversed string back to an integer using the int() function

Implementation: 

C++
Java Python C# JavaScript

Output
Reverse of 12345 is 54321

Time complexity: O(n), where n is the number of digits in the integer.
Space complexity: O(n), where n is the number of digits in the integer, since we need to create a string of length n to store the reversed integer.


Next Article
Article Tags :
Practice Tags :

Similar Reads