Reverse digits of an integer with overflow handled
Last Updated :
23 Jul, 2025
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++
// A simple C program to reverse digits of
// an integer.
#include <bits/stdc++.h>
using namespace std;
int reversDigits(int num)
{
int rev_num = 0;
while (num != 0) {
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
/* Driver program to test reversDigits */
int main()
{
int num = 5896;
cout << "Reverse of no. is " << reversDigits(num);
return 0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
// This code is improved by Md. Owais Ashraf (professor_011)
C
// A simple C program to reverse digits of
// an integer.
#include <stdio.h>
int reversDigits(int num)
{
int rev_num = 0;
while (num != 0) {
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
/* Driver program to test reversDigits */
int main()
{
int num = 5896;
printf("Reverse of no. is %d", reversDigits(num));
return 0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
// This code is improved by Md. Owais Ashraf (professor_011)
Java
// Java program to reverse a number
class GFG
{
/* Iterative function to reverse
digits of num*/
static int reversDigits(int num)
{
int rev_num = 0;
while(num!=0)
{
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
// Driver code
public static void main (String[] args)
{
int num = 5896;
System.out.println("Reverse of no. is "
+ reversDigits(num));
}
}
// This code is contributed by Anant Agarwal.
// This code is improved by Md. Owais Ashraf (professor_011)
// This code is improved by Jeet Purohit (jeetpurohit989)
Python
# Python program to reverse a number
n = 5896;
rev = 0
while(n != 0):
a = n % 10
rev = rev * 10 + a
n = n // 10
print(rev)
# This code is contributed by Shariq Raza
# This code is improved by Jeet Purohit (jeetpurohit989)
C#
// C# program to reverse a number
using System;
class GFG
{
// Iterative function to
// reverse digits of num
static int reversDigits(int num)
{
int rev_num = 0;
while(num != 0)
{
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
// Driver code
public static void Main()
{
int num = 5896;
Console.Write("Reverse of no. is "
+ reversDigits(num));
}
}
// This code is contributed by Sam007
// This code is improved by Md. Owais Ashraf (professor_011)
JavaScript
<script>
// A simple Javascript program to reverse digits of
// an integer.
function reversDigits(num)
{
let rev_num = 0;
while (num != 0)
{
rev_num = rev_num*10 + num%10;
num = Math.floor(num/10);
}
return rev_num;
}
/* Driver program to test reversDigits */
let num = 5896;
document.write("Reverse of no. is "+ reversDigits(num));
// This code is contributed by Mayank Tyagi
// This code is improved by Md. Owais Ashraf (professor_011)
// This code is improved by Jeet Purohit (jeetpurohit989)
</script>
PHP
<?php
// Iterative function to
// reverse digits of num
function reversDigits($num)
{
$rev_num = 0;
while($num != 0)
{
$rev_num = $rev_num * 10 +
$num % 10;
$num = (int)$num / 10;
}
return $rev_num/10;
}
// Driver Code
$num = 5896;
echo "Reverse of no. is ",
reversDigits($num);
// This code is contributed by aj_36
// This code is improved by Md. Owais Ashraf (professor_011)
// This code is improved by Jeet Purohit (jeetpurohit989)
?>
OutputReverse 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++ program to reverse digits
// of a number
#include <bits/stdc++.h>
using namespace std;
/* Iterative function to reverse
digits of num*/
int reversDigits(int num)
{
// Handling negative numbers
bool negativeFlag = false;
if (num < 0)
{
negativeFlag = true;
num = -num ;
}
int prev_rev_num = 0, rev_num = 0;
while (num != 0)
{
int curr_digit = num % 10;
rev_num = (rev_num * 10) + curr_digit;
// checking if the reverse overflowed or not.
// The values of (rev_num - curr_digit)/10 and
// prev_rev_num must be same if there was no
// problem.
if ((rev_num - curr_digit) /
10 != prev_rev_num)
{
cout << "WARNING OVERFLOWED!!!"
<< endl;
return 0;
}
prev_rev_num = rev_num;
num = num / 10;
}
return (negativeFlag == true) ?
-rev_num : rev_num;
}
// Driver Code
int main()
{
int num = 12345;
cout << "Reverse of no. is "
<< reversDigits(num) << endl;
num = 1000000045;
cout << "Reverse of no. is "
<< reversDigits(num) << endl;
return 0;
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
C
// C program to reverse digits of a number
#include <stdio.h>
/* Iterative function to reverse digits of num*/
int reversDigits(int num)
{
// Handling negative numbers
bool negativeFlag = false;
if (num < 0)
{
negativeFlag = true;
num = -num ;
}
int prev_rev_num = 0, rev_num = 0;
while (num != 0)
{
int curr_digit = num%10;
rev_num = (rev_num*10) + curr_digit;
// checking if the reverse overflowed or not.
// The values of (rev_num - curr_digit)/10 and
// prev_rev_num must be same if there was no
// problem.
if ((rev_num - curr_digit)/10 != prev_rev_num)
{
printf("WARNING OVERFLOWED!!!\n");
return 0;
}
prev_rev_num = rev_num;
num = num/10;
}
return (negativeFlag == true)? -rev_num : rev_num;
}
/* Driver program to test reverse Digits */
int main()
{
int num = 12345;
printf("Reverse of no. is %d\n", reversDigits(num));
num = 1000000045;
printf("Reverse of no. is %d\n", reversDigits(num));
return 0;
}
Java
// Java program to reverse digits of a number
class ReverseDigits
{
/* Iterative function to reverse digits of num*/
static int reversDigits(int num)
{
// Handling negative numbers
boolean negativeFlag = false;
if (num < 0)
{
negativeFlag = true;
num = -num ;
}
int prev_rev_num = 0, rev_num = 0;
while (num != 0)
{
int curr_digit = num%10;
rev_num = (rev_num*10) + curr_digit;
// checking if the reverse overflowed or not.
// The values of (rev_num - curr_digit)/10 and
// prev_rev_num must be same if there was no
// problem.
if ((rev_num - curr_digit)/10 != prev_rev_num)
{
System.out.println("WARNING OVERFLOWED!!!");
return 0;
}
prev_rev_num = rev_num;
num = num/10;
}
return (negativeFlag == true)? -rev_num : rev_num;
}
public static void main (String[] args)
{
int num = 12345;
System.out.println("Reverse of no. is " + reversDigits(num));
num = 1000000045;
System.out.println("Reverse of no. is " + reversDigits(num));
}
}
Python
# Python program to reverse digits
# of a number
""" Iterative function to reverse
digits of num"""
def reversDigits(num):
# Handling negative numbers
negativeFlag = False
if (num < 0):
negativeFlag = True
num = -num
prev_rev_num = 0
rev_num = 0
while (num != 0):
curr_digit = num % 10
rev_num = (rev_num * 10) + curr_digit
# checking if the reverse overflowed or not.
# The values of (rev_num - curr_digit)/10 and
# prev_rev_num must be same if there was no
# problem.
if (rev_num >= 2147483647 or
rev_num <= -2147483648):
rev_num = 0
if ((rev_num - curr_digit) // 10 != prev_rev_num):
print("WARNING OVERFLOWED!!!")
return 0
prev_rev_num = rev_num
num = num //10
return -rev_num if (negativeFlag == True) else rev_num
# Driver code
if __name__ =="__main__":
num = 12345
print("Reverse of no. is ",reversDigits(num))
num = 1000000045
print("Reverse of no. is ",reversDigits(num))
# This code is contributed
# Shubham Singh(SHUBHAMSINGH10)
C#
// C# program to reverse digits
// of a number
using System;
class GFG
{
/* Iterative function to reverse
digits of num*/
static int reversDigits(int num)
{
// Handling negative numbers
bool negativeFlag = false;
if (num < 0)
{
negativeFlag = true;
num = -num ;
}
int prev_rev_num = 0, rev_num = 0;
while (num != 0)
{
int curr_digit = num % 10;
rev_num = (rev_num * 10) +
curr_digit;
// checking if the reverse overflowed
// or not. The values of (rev_num -
// curr_digit)/10 and prev_rev_num must
// be same if there was no problem.
if ((rev_num - curr_digit) / 10 != prev_rev_num)
{
Console.WriteLine("WARNING OVERFLOWED!!!");
return 0;
}
prev_rev_num = rev_num;
num = num / 10;
}
return (negativeFlag == true) ?
-rev_num : rev_num;
}
// Driver Code
static public void Main ()
{
int num = 12345;
Console.WriteLine("Reverse of no. is " +
reversDigits(num));
num = 1000000045;
Console.WriteLine("Reverse of no. is " +
reversDigits(num));
}
}
// This code is contributed by ajit
JavaScript
<script>
// JavaScript program to reverse digits
// of a number
/* Iterative function to reverse
digits of num*/
function reversDigits(num)
{
// Handling negative numbers
let negativeFlag = false;
if (num < 0)
{
negativeFlag = true;
num = -num ;
}
let prev_rev_num = 0, rev_num = 0;
while (num != 0)
{
let curr_digit = num % 10;
rev_num = (rev_num * 10) + curr_digit;
// checking if the reverse overflowed or not.
// The values of (rev_num - curr_digit)/10 and
// prev_rev_num must be same if there was no
// problem.
if (rev_num >= 2147483647 ||
rev_num <= -2147483648)
rev_num = 0;
if (Math.floor((rev_num - curr_digit) / 10) != prev_rev_num)
{
document.write("WARNING OVERFLOWED!!!"
+ "<br>");
return 0;
}
prev_rev_num = rev_num;
num = Math.floor(num / 10);
}
return (negativeFlag == true) ?
-rev_num : rev_num;
}
// Driver Code
let num = 12345;
document.write("Reverse of no. is "
+ reversDigits(num) + "<br>");
num = 1000000045;
document.write("Reverse of no. is "
+ reversDigits(num) + "<br>");
// This code is contributed by Surbhi Tyagi.
</script>
OutputReverse 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++
// C++ program to reverse digits
// of a number
#include <bits/stdc++.h>
using namespace std;
int reversDigits(int num) {
int rev = 0 ;
while(num != 0){
int rem = num % 10 ;
num /= 10 ;
if(rev > INT_MAX/10 || rev < INT_MIN/10){
return 0 ;
}
rev = rev*10 + rem ;
}
return rev ;
}
// Driver Code
int main()
{
int num = 12345;
cout << "Reverse of no. is "
<< reversDigits(num) << endl;
num = 1000000045;
cout << "Reverse of no. is "
<< reversDigits(num) << endl;
return 0;
}
Java
// Java program to reverse digits
// of a number
public class GFG
{
static int reversDigits(int num)
{
int rev = 0 ;
while(num != 0){
int rem = num % 10 ;
num /= 10 ;
if(rev > Integer.MAX_VALUE/10 || rev == Integer.MAX_VALUE/10 && rem > 7){
return 0 ;
}
if(rev < Integer.MIN_VALUE/10 || rev == Integer.MIN_VALUE/10 && rem < -8){
return 0 ;
}
rev = rev*10 + rem ;
}
return rev ;
}
// Driver code
public static void main (String[] args)
{
int num = 12345;
System.out.println("Reverse of no. is " + reversDigits(num) );
num = 1000000045;
System.out.println("Reverse of no. is " + reversDigits(num) );
}
}
// This code is contributed by jana_sayantan.
Python
def reverse_digits(num):
# Initialize reverse number as 0
rev = 0
# Check sign of the number
sign = -1 if num < 0 else 1
# Take absolute value of the number
num = abs(num)
# Reverse the digits
while num != 0:
# Get the last digit
rem = num % 10
# Remove the last digit from the number
num = num // 10
# Check if the reverse number will overflow 32-bit integer
if rev > 2**31//10 or (rev == 2**31//10 and rem > 7):
return 0
# Check if the reverse number will underflow 32-bit integer
if rev < -2**31//10 or (rev == -2**31//10 and rem < -8):
return 0
# Update the reverse number
rev = rev * 10 + rem
# Return the reverse number with the original sign
return sign * rev
if __name__ == '__main__':
num = 12345
print("Reverse of no. is", reverse_digits(num))
num = 1000000045
print("Reverse of no. is", reverse_digits(num))
C#
// C# program to reverse digits
// of a number
using System;
public class GFG
{
static int reversDigits(int num)
{
int rev = 0 ;
while(num != 0){
int rem = num % 10 ;
num /= 10 ;
if(rev > Int32.MaxValue/10 || rev == Int32.MaxValue/10 && rem > 7){
return 0 ;
}
if(rev < Int32.MinValue/10 || rev == Int32.MinValue/10 && rem < -8){
return 0 ;
}
rev = rev*10 + rem ;
}
return rev ;
}
// Driver code
public static void Main (string[] args)
{
int num = 12345;
Console.WriteLine("Reverse of no. is " + reversDigits(num) );
num = 1000000045;
Console.WriteLine("Reverse of no. is " + reversDigits(num) );
}
}
// This code is contributed by phasing17
JavaScript
<script>
// JavaScript program to reverse digits
// of a number
const INT_MAX = 2147483647;
const INT_MIN = -2147483648;
function reversDigits(num) {
let rev = 0;
while(num > 0){
let rem = num % 10 ;
num = Math.floor(num/10) ;
if(rev > INT_MAX/10 || rev == INT_MAX/10 && rem > 7){
return 0 ;
}
if(rev < INT_MIN/10 || rev == INT_MIN/10 && rem < -8){
return 0 ;
}
rev = rev*10 + rem ;
}
return rev ;
}
// Driver Code
let num = 12345;
document.write(`Reverse of no. is ${reversDigits(num)}`,"</br>");
num = 1000000045;
document.write(`Reverse of no. is ${reversDigits(num)}`,"</br>");
// This code is contributed by shinjanpatra
</script>
OutputReverse 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++
#include <iostream>
#include <string>
int reverseNumStringSlice(int num)
{
// Convert the integer to a string
std::string numStr = std::to_string(num);
// Reverse the string using the slice operator
std::string reversedStr(numStr.rbegin(), numStr.rend());
// Convert the reversed string back to an integer
int reversedNum = std::stoi(reversedStr);
return reversedNum;
}
int main()
{
int num = 12345;
int revNumStringSlice = reverseNumStringSlice(num);
std::cout << "Reverse of " << num << " is "
<< revNumStringSlice << std::endl;
return 0;
}
Java
public class ReverseNumStringSlice {
// Function to reverse an integer using string slice
static int reverseNumStringSlice(int num)
{
// Convert the integer to a string
String numStr = Integer.toString(num);
// Reverse the string using the substring method
String reversedStr = new StringBuilder(numStr)
.reverse()
.toString();
// Convert the reversed string back to an integer
int reversedNum = Integer.parseInt(reversedStr);
return reversedNum;
}
// Main method
public static void main(String[] args)
{
// Example integer
int num = 12345;
// Call the reverseNumStringSlice function
int revNumStringSlice = reverseNumStringSlice(num);
// Output the result
System.out.println("Reverse of " + num + " is "
+ revNumStringSlice);
}
}
Python
def reverse_num_string_slice(num):
return int(str(num)[::-1])
num = 12345
rev_num_string_slice = reverse_num_string_slice(num)
print(f"Reverse of {num} is {rev_num_string_slice}")
C#
using System;
class Program {
static int ReverseNumStringSlice(int num)
{
// Convert the integer to a string
string numStr = num.ToString();
// Reverse the string using the slice operator
char[] charArray = numStr.ToCharArray();
Array.Reverse(charArray);
string reversedStr = new string(charArray);
// Convert the reversed string back to an integer
int reversedNum = int.Parse(reversedStr);
return reversedNum;
}
static void Main()
{
int num = 12345;
int revNumStringSlice = ReverseNumStringSlice(num);
Console.WriteLine("Reverse of " + num + " is "
+ revNumStringSlice);
}
}
JavaScript
function GFG(num) {
// Convert the integer to a string
const numStr = num.toString();
// Reverse the string using slice operator
const reversedStr = numStr.split('').reverse().join('');
// Convert the reversed string back to an integer
const reversedNum = parseInt(reversedStr, 10);
return reversedNum;
}
// Main function
function main() {
const num = 12345;
// Call the function to the reverse the number
const revNumStringSlice = GFG(num);
// Display the result
console.log(`Reverse of ${num} is ${revNumStringSlice}`);
}
main();
OutputReverse 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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem