Dígitos inversos de un entero con desbordamiento manejado

Escriba un programa para invertir un entero suponiendo que la entrada es un entero de 32 bits. Si el entero invertido se desborda, imprima -1 como salida. 
Veamos un enfoque simple para invertir los dígitos de un número entero
 

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)

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)

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 = 4562;
        System.out.println("Reverse of no. is "
                           + reversDigits(num));
    }
}
 
// This code is contributed by Anant Agarwal.

Python3

# Python program to reverse a number
 
n = 4562;
rev = 0
 
while(n > 0):
    a = n % 10
    rev = rev * 10 + a
    n = n // 10
     
print(rev)
 
# This code is contributed by Shariq Raza

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 = 4562;
        Console.Write("Reverse of no. is "
                        + reversDigits(num));
    }
}
 
// This code is contributed by Sam007

PHP

<?php
// Iterative function to
// reverse digits of num
function reversDigits($num)
{
    $rev_num = 0;
    while($num > 1)
    {
        $rev_num = $rev_num * 10 +
                        $num % 10;
        $num = (int)$num / 10;
    }
    return $rev_num;
}
 
// Driver Code
$num = 4562;
echo "Reverse of no. is ",
       reversDigits($num);
 
// This code is contributed by aj_36
?>

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
 
</script>
Producción

Reverse of no. is 6985

Complejidad de tiempo: O(log(num))

Espacio Auxiliar: O(1)

Sin embargo, si el número es tan grande que el reverso se desborda, la salida es un valor basura. Si ejecutamos el código anterior con la entrada como cualquier número grande, digamos 1000000045 , entonces la salida es un valor basura como 1105032705 o cualquier otro valor basura. Ver esto para la salida.
¿Cómo manejar el desbordamiento?  
La idea es almacenar el valor anterior de la suma en una variable que se puede verificar cada vez para ver si el reverso se desbordó o no.
A continuación se muestra la implementación para hacer frente a tal situación.
 

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));
    }
}

Python3

# 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>
Producción

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

Complejidad de tiempo: O(log(num))

Espacio Auxiliar: O(1)

Enfoque eficiente:

El enfoque anterior no funcionará si nos dan un entero x de 32 bits con signo, devolvemos x con sus dígitos invertidos. Si invertir x hace que el valor salga del rango de enteros de 32 bits con signo [-231, 231 – 1], devuelva 0.

Entonces no podemos multiplicar el número*10 y luego verificar si el número se desborda o no.

Debemos verificar la condición de desbordamiento antes de multiplicar por 10 usando la siguiente lógica:

Está verificando el caso límite antes de realizar la operación. (invertido > INT_MAX ) no funcionaría 

porque invertido se desbordará y se volverá negativo si supera MAX_VALUE. 

Dividir MAX_VALUE por 10 le permite verificar la condición sin desbordarse

INT_MAX es igual a 2147483647. INT_MIN es igual a -2147483648. 

Los últimos dígitos son 7 y 8. Esta es la razón por la que también verificamos las condiciones rem > 7 y rem < -8

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_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
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.

Python3

# Python program for the above approach
INT_MAX = 2147483647
INT_MIN = -2147483648
 
def reversDigits(num):
     
    rev = 0
     
    while(num > 0):   
        rem = num % 10
        num = (num//10)
         
        if(rev > INT_MAX/10 or rev == INT_MAX/10 and rem > 7):
            return 0
         
        if(rev < INT_MIN/10 or rev == INT_MIN/10 and rem < -8):
            return 0
         
        rev = rev*10 + rem
     
    return rev
 
# Driver Code
num = 12345
print(f"Reverse of no. is {reversDigits(num)}")
 
num = 1000000045
print(f"Reverse of no. is {reversDigits(num)}")
 
# This code is contributed by shinjanpatra

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>
Producción

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

Complejidad de tiempo: O(log(num))

Espacio Auxiliar: O(1)

Este artículo es una contribución de MAZHAR IMAM KHAN . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *