¿Cómo resolver problemas relacionados con Número-Dígitos usando Recursión?

El proceso en el que una función se llama a sí misma directa o indirectamente se llama recursividad y la función correspondiente se llama función recursiva. Usando un algoritmo recursivo, ciertos problemas se pueden resolver con bastante facilidad. En este artículo se analiza un método para resolver los problemas de dígitos numéricos mediante recursividad. 
Existen dos componentes principales para cualquier función recursiva: 
 

  1. Caso base: Un caso base es una condición que detiene las llamadas a funciones recursivas. No se puede formar una función recursiva sin un caso base porque el error de desbordamiento de pila ocurre cuando el caso base no está definido, ya que la función seguirá llamándose a sí misma repetidamente. Para una solución recursiva, puede haber más de un caso base.
  2. Caso recursivo: para todas las demás condiciones, aparte de los casos base, la función se llama a sí misma con un nuevo conjunto de valores, de modo que después de algunas llamadas recursivas finitas, la función finalmente llama a un caso base y se detiene.

Visualicemos la recursión extrayendo dígitos individuales de un número dado. Este es el paso básico para realizar muchas otras operaciones matemáticas. 
A continuación se muestra la implementación para extraer cada dígito individual de un número: 
 

C++

// Recursive function to extract
// individual digit for a given
// number
#include<bits/stdc++.h>
using namespace std;
 
void extract(int n){
 
    // If n is a zero
    // then, stop the recursion
    if(n == 0)
    {
        return;
    }
 
   
    // Call the function recursively
    // for n // 10 which basically
    // calls for the remaining number
    // after removing the last digit
    extract(n / 10);
     
      // print the current last digit of the number
      // with n%10;
    cout << n % 10 << endl;
 
}
 
// Driver code
int main()
{
    extract(1234);
    return 0;
}
 
// This code is contributed by 29AjayKumar

Java

// Recursive function to extract
// individual digit for a given
// number
class GFG{
 
static void extract(int n)
{
     
    // If n is a zero
    // then, stop the recursion
    if(n == 0)
    {
        return;
    }
 
    // Call the function recursively
    // for n/10 which basically
    // calls for the remaining number
    // after removing the last digit
    extract(n / 10);
   
      // print the current last digit of the number
      // with n%10;
      System.out.println(n%10);
}
 
// Driver code
public static void main(String[] args)
{
    extract(1234);
}
}
 
// This code is contributed by Rohit_ranjan

Python3

# Recursive function to extract
# individual digit for a given
# number
def extract(n):
 
    # If n is a zero
    # the stop the recursion
    if(n == 0):
        return
 
    # Call the function recursively
    # for n // 10 which basically
    # calls for the remaining number
    # after removing the last digit
    extract(n//10)
     
    # print the last digit with n%10
    print(n % 10)
 
     
# Driver code
if __name__ == "__main__":
    extract(1234)

C#

// Recursive function to extract
// individual digit for a given
// number
using System;
 
class GFG{
     
static void extract(int n)
{
     
   // If n is a zero
   // then, stop the recursion
    if(n  == 0)
    {
        return;
    }
 
    // Call the function recursively
    // for n // 10 which basically
    // calls for the remaining number
    // after removing the last digit
    extract(n / 10);
   
      // print the current last digit of the number
      // with n%10;
    Console.Write(n % 10 + "\n");
 
}
 
// Driver code
public static void Main(String[] args)
{
    extract(1234);
}
}
 
// This code is contributed by sapnasingh4991

Javascript

<script>
 
    // Recursive function to extract
    // individual digit for a given number
     
    function extract(n)
    {
 
        // If n is a zero
        // then stop the recursion
        if(parseInt(n) == 0)
        {
            return;
        }
         
        // Call the function recursively
        // for n // 10 which basically
        // calls for the remaining number
        // after removing the last digit
        extract(parseInt(n / 10, 10));
         
        // print the current last digit of the number
          // with n%10;
        document.write(n % 10 + "</br>");
 
    }
     
    extract(1001);
 
</script>
Producción

1
2
3
4

Similar a esto, se pueden realizar varias otras operaciones usando la recursividad. Cada función iterativa se puede calcular usando la recursividad. 
 

Publicación traducida automáticamente

Artículo escrito por aneesh_reddy 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 *