Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Write an Efficient C Program to Reverse Bits of a Number
Next article icon

Reverse digits of an integer with overflow handled | Set 2

Last Updated : 29 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a 32-bit integer N. The task is to reverse N, if the reversed integer overflows, print -1 as the output.

Examples

Input: N = 123
Output: 321

Input: N = -123
Output: -321

Input: N = 120
Output: 21

 

Approach: Unlike approaches Set 1 of the article, this problem can be solved simply by using a 64-bit data structure and range of int data type [-2^31, 2^31 - 1]

  • Copy the value of the given number N in a long variable
  • Check if it is negative
  • Now reverse the long number digit by digit, and if at any step, its value goes out of range the int type, return 0.
  • Make the resultant number negative if the given number is negative
  • Again check for the number to be in int range. If yes return 0, else return the reversed number.

Below is the implementation of the above approach.

C++
// C++ program for above approach #include <bits/stdc++.h>  // Function to reverse digits in a number int reverseDigits(int N) {     // Taking a long variable     // to store the number     long m = N;      int neg = m < 0 ? -1 : 1;      if (m * neg < pow(-2, 31)         || m * neg >= pow(2, 31))         return 0;     m = m * neg;     long n = 0;      while (m > 0) {         if (n * 10 < pow(-2, 31)             || n * 10 >= pow(2, 31))             return 0;         n = n * 10 + m % 10;         m = m / 10;     }     if (n * neg < pow(-2, 31)         || n * neg >= pow(2, 31))         return 0;     n = n * neg;     return n; }  // Driver Code int main() {     int N = 5896;     printf("Reverse of no. is %d",            reverseDigits(N));     return 0; } 
Java
// Java program for above approach class GFG {    // Function to reverse digits in a number   static int reverseDigits(int N) {      // Taking a long variable     // to store the number     long m = N;      int neg = m < 0 ? -1 : 1;      if (m * neg < Math.pow(-2, 31)         || m * neg >= Math.pow(2, 31))       return 0;     m = m * neg;     long n = 0;      while (m > 0) {       if (n * 10 < Math.pow(-2, 31)           || n * 10 >= Math.pow(2, 31))         return 0;       n = n * 10 + m % 10;       m = m / 10;     }     if (n * neg < Math.pow(-2, 31)         || n * neg >= Math.pow(2, 31))       return 0;     n = n * neg;     return (int) n;   }    // Driver Code   public static void main(String args[]) {     int N = 5896;     System.out.println("Reverse of no. is " + reverseDigits(N));   } }  // This code is contributed by Saurabh Jaiswal 
Python3
# Python code for the above approach  # Function to reverse digits in a number def reverseDigits(N):      # Taking a long variable     # to store the number     m = N      neg = -1 if m < 0 else 1      if (m * neg < (-2 ** 31) or m * neg >= (2 ** 31)):         return 0     m = m * neg     n = 0      while (m > 0):         if (n * 10 < (-2 ** 31) or n * 10 >= (2 ** 31)):             return 0         n = n * 10 + m % 10         m = (m // 10)     if (n * neg < (-2 ** 31) or n * neg >= (2 ** 31)):         return 0     n = n * neg     return n  # Driver Code N = 5896 print(f"Reverse of no. is  {reverseDigits(N)}")  # This code is contributed by gfgking 
C#
// C# program for above approach using System; class GFG {    // Function to reverse digits in a number   static int reverseDigits(int N)   {      // Taking a long variable     // to store the number     long m = N;      int neg = m < 0 ? -1 : 1;      if (m * neg < Math.Pow(-2, 31)         || m * neg >= Math.Pow(2, 31))       return 0;     m = m * neg;     long n = 0;      while (m > 0) {       if (n * 10 < Math.Pow(-2, 31)           || n * 10 >= Math.Pow(2, 31))         return 0;       n = n * 10 + m % 10;       m = m / 10;     }     if (n * neg < Math.Pow(-2, 31)         || n * neg >= Math.Pow(2, 31))       return 0;     n = n * neg;     return (int)n;   }    // Driver Code   public static void Main()   {     int N = 5896;     Console.Write("Reverse of no. is " + reverseDigits(N));   } }  // This code is contributed by Samim Hossain Mondal. 
JavaScript
<script>         // JavaScript code for the above approach           // Function to reverse digits in a number         function reverseDigits(N)         {                      // Taking a long variable             // to store the number             let m = N;              let neg = m < 0 ? -1 : 1;              if (m * neg < Math.pow(-2, 31)                 || m * neg >= Math.pow(2, 31))                 return 0;             m = m * neg;             let n = 0;              while (m > 0) {                 if (n * 10 < Math.pow(-2, 31)                     || n * 10 >= Math.pow(2, 31))                     return 0;                 n = n * 10 + m % 10;                 m = Math.floor(m / 10);             }             if (n * neg < Math.pow(-2, 31)                 || n * neg >= Math.pow(2, 31))                 return 0;             n = n * neg;             return n;         }          // Driver Code         let N = 5896;         document.write(`Reverse of no. is              ${reverseDigits(N)}`);           // This code is contributed by Potta Lokesh     </script> 

 
 


Output
Reverse of no. is 6985

Time Complexity: O(D), where D is the number of digits in N.  
Auxiliary Space: O(1)

Another Approach:

  1. Define a function "reverse" that takes an integer "n" as input.
    1. Initialize a variable "rev" to 0 to store the reversed integer.
    2. Iterate through each digit of the input integer by dividing it by 10 until it becomes 0.
      1. In each iteration, find the remainder of the input integer when divided by 10, which gives the current digit.
      2. Check if the current value of "rev" will cause an overflow or underflow when multiplied by 10 and added to the current digit.
      3. If it will cause an overflow or underflow, return -1 to indicate that the reversed integer has overflowed.
      4. Otherwise, multiply the current value of "rev" by 10 and add the current digit to it to reverse the integer.
    3. After reversing the integer, print the value of "rev".

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <iostream>  // required for INT_MAX and INT_MIN constants #include <limits.h> using namespace std;  // Function to reverse the digit int reverse(int n) {     int rev = 0;     while (n != 0) {         int rem = n % 10;          // overflow condition         if (rev > INT_MAX / 10             || (rev == INT_MAX / 10 && rem > 7)) {             return -1;         }          // underflow condition         if (rev < INT_MIN / 10             || (rev == INT_MIN / 10 && rem < -8)) {             return -1;         }         rev = rev * 10 + rem;         n /= 10;     }     return rev; }  // Driver Code int main() {     int n = 5896;     int rev = reverse(n);     if (rev == -1) {         cout << "-1" << endl;     }     else {         cout << rev << endl;     }     return 0; } 
Java
import java.util.*;  public class Main {      // Function to reverse the digit     public static int reverse(int n) {         int rev = 0;         while (n != 0) {             int rem = n % 10;              // overflow condition             if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && rem > 7)) {                 return -1;             }              // underflow condition             if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && rem < -8)) {                 return -1;             }             rev = rev * 10 + rem;             n /= 10;         }         return rev;     }      // Driver Code     public static void main(String[] args) {         int n = 5896;         int rev = reverse(n);         if (rev == -1) {             System.out.println("-1");         } else {             System.out.println(rev);         }     } } // This code is contributed by rudra1807raj 
Python3
def reverse(n):     rev = 0     while n != 0:         rem = n % 10          # Overflow condition         if rev > 2**31 // 10 or (rev == 2**31 // 10 and rem > 7):             return -1          # Underflow condition         if rev < -2**31 // 10 or (rev == -2**31 // 10 and rem < -8):             return -1          rev = rev * 10 + rem         n //= 10      return rev  # Driver Code n = 5896 rev = reverse(n)  if rev == -1:     print("-1") else:     print(rev) 
C#
using System;  public class GFG {     // Function to reverse the digit     public static int Reverse(int n)     {         int rev = 0;         while (n != 0) {             int rem = n % 10;              // overflow condition             if (rev > int.MaxValue / 10                 || (rev == int.MaxValue / 10 && rem > 7)) {                 return -1;             }              // underflow condition             if (rev < int.MinValue / 10                 || (rev == int.MinValue / 10 && rem < -8)) {                 return -1;             }              rev = rev * 10 + rem;             n /= 10;         }         return rev;     }      public static void Main()     {         int n = 5896;         int rev = Reverse(n);         if (rev == -1) {             Console.WriteLine("-1");         }         else {             Console.WriteLine(rev);         }     } } 
JavaScript
// JavaScript program for the above approach  // Function to reverse the digit function reverse(n) { let rev = 0; while (n !== 0) { let rem = n % 10;   // overflow condition if (rev > Number.MAX_SAFE_INTEGER / 10 ||     (rev === Number.MAX_SAFE_INTEGER / 10 && rem > 7)) {   return -1; }  // underflow condition if (rev < Number.MIN_SAFE_INTEGER / 10 ||     (rev === Number.MIN_SAFE_INTEGER / 10 && rem < -8)) {   return -1; }  rev = rev * 10 + rem; n = Math.trunc(n / 10); } return rev; }  // Driver Code let n = 5896; let rev = reverse(n); if (rev === -1) { console.log("-1"); } else { console.log(rev); }  // This code is contributed by rudra1807raj 

Output
6985

Time Complexity: The reverse() function iterates through each digit of the input integer n, so the time complexity of the function is O(log n), where n is the magnitude of the input integer.
Auxiliary Space: The space complexity is O(1)


Next Article
Write an Efficient C Program to Reverse Bits of a Number

C

code_r
Improve
Article Tags :
  • Misc
  • Mathematical
  • DSA
  • number-digits
  • Reverse
Practice Tags :
  • Mathematical
  • Misc
  • Reverse

Similar Reads

  • Reverse digits of an integer with overflow handled
    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. [GFGTABS] C++ // A simple C program to reverse digits of // an integer. #include <bits/stdc++
    15 min read
  • Write an Efficient C Program to Reverse Bits of a Number
    Given an unsigned integer, reverse all bits of it and return the number with reversed bits. Input : n = 1Output : 2147483648 Explanation : On a machine with size of unsigned bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648Output : 1 Recommended PracticeReverse BitsTry It!Method1 -
    6 min read
  • Find One’s Complement of an Integer | Set 2
    Given an integer N, find the one’s complement of the integer. Examples: Input: N = 5Output: 2Explanation: Binary representation of 5 is "101". Its one's complement is "010" = 2. Input: N = 255Output: 0 Input: N = 26Output: 5 Approach: Already the XOR-based approach and converting the number to binar
    3 min read
  • Reverse bits of a positive integer number in Python
    Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.Examples: Input : n = 1, bitSize=32 Output : 2147483648 On a machine with size of bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648, bitSize=32 Output : 1 We can solve this pr
    4 min read
  • Previous smaller integer having one less number of set bits
    Given a positive integer ‘n’ having ‘x’ number of set bits in its binary representation. The problem is to find the previous smaller integer(greatest integer smaller than n), having (x-1) number of set bits in its binary representation.Note: 1 <= n Examples : Input : 8 Output : 0 (8)10 = (1000)2
    4 min read
  • Reverse actual bits of the given number
    Given a non-negative integer n, the task is to reverse the bits in its binary representation and return the resulting decimal number. The reversal should consider only the actual binary digits without any leading zeros. Examples : Input : 11Output : 13Explanation: (11)10 = (1011)2.After reversing th
    4 min read
  • Check if a given number is one less than twice its reverse
    Given an integer N, the task is to check if it is a solution to the equation 2 * reverse(N) - 1 = N Examples: Input: N = 73Output: YesExplanation:2 * reverse(N) = 2 * 37 = 74N + 1 = 73 + 1 = 74 Input: N = 83Output: No Naive Approach: The simplest approach is to find the reverse of the given number a
    7 min read
  • Set all the bits in given range of a number
    Given a non-negative number n and two values l and r. The problem is to set the bits in the range l to r in the binary representation of n, i.e, to unset bits from the rightmost lth bit to the rightmost r-th bit. Constraint: 1 <= l <= r <= number of bits in the binary representation of n.Ex
    5 min read
  • Program to find last two digits of 2^n
    Given a number n, we need to find the last two digits of 2n. Examples: Input : n = 7 Output : 28 Input : n = 72 Output : 96 2^72 = 4722366482869645213696 A Naive Approach is to find the value of 2^n iteratively or using pow function. Once the value of 2^n is calculated, find the last two digits and
    15 min read
  • Find the largest number with n set and m unset bits
    Given two non-negative numbers n and m. The problem is to find the largest number having n number of set bits and m number of unset bits in its binary representation.Note : 0 bits before leading 1 (or leftmost 1) in binary representation are countedConstraints: 1 <= n, 0 <= m, (m+n) <= 31Ex
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences