Open In App

# Reverse digits of an integer with overflow handled | Set 2

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 ` `// 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

 ``

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 ` `// required for INT_MAX and INT_MIN constants``#include ``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`

## 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)