Reduzca el número a un solo dígito restando los dígitos adyacentes repetidamente

Dado un número N , la tarea es reducirlo a un número de un solo dígito restando repetidamente los dígitos adyacentes. Es decir, en la primera iteración, resta todos los dígitos adyacentes para generar un nuevo número, si este número contiene más de un dígito, repite el mismo proceso hasta que se convierta en un número de un solo dígito.

Ejemplos: 

Entrada: N = 6972 
Salida:
| 6 – 9 | = 3 
| 9 – 7 | = 2 
| 7 – 2 | = 5
Después del primer paso, obtenemos 325 , pero 325 no es un número de un solo dígito, por lo que lo reduciremos aún más hasta que no obtengamos un número de un solo dígito.
| 3 – 2 | = 1 
| 2 – 5 | = 3
Y ahora el número será 13 , lo reduciremos aún más 
| 1 – 3 | = 2
Entrada: N = 123456 
Salida:
 

Enfoque: aquí estamos usando Array para representar el número inicial N por simplicidad.  

  1. Cuente el número de dígitos en N y almacene el valor en l
     
  2. Cree una array a[] de tamaño l
     
  3. Copie el número dado en la array a[]
     
  4. Calcule el RSF restando los dígitos consecutivos de la array a
     

A continuación se muestra la implementación del enfoque anterior:  

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the resultant digit
// after performing the given operations
int RSF(int n)
{
    while (n >= 10) {
 
        // Creating an extra copy of n
        int x = n;
        int l = 0;
 
        // Counting the number of digits in n
        while (n > 0) {
            n = n / 10;
            l++;
        }
 
        // Now n is 0
        // Creating an array of length l
        int a[l];
 
        // Initializing i with the last index of array
        int i = l - 1;
        while (x > 0) {
 
            // Filling array from right to left
            a[i] = x % 10;
            x = x / 10;
            i--;
        }
 
        // Calculating the absolute consecutive difference
        for (int j = 0; j < l - 1; j++) {
 
            // Updating the value of n in every loop
            n = n * 10 + abs(a[j] - a[j + 1]);
        }
    }
 
    // While loop ends here and we have found
    // the RSF value of N
    return n;
}
 
// Driver code
int main()
{
    int n = 614;
 
    // Passing n to RSF function and getting answer
    int ans = RSF(n);
 
    // Printing the value stored in ans
    cout << ans;
 
    return 0;
}

Java

// Java implementation of the approach
class GFG {
 
    // Function to return the resultant digit
    // after performing the given operations
    static int RSF(int n)
    {
        while (n >= 10) {
 
            // Creating an extra copy of n
            int x = n;
            int l = 0;
 
            // Counting the number of digits in n
            while (n > 0) {
                n = n / 10;
                l++;
            }
 
            // Now n is 0
            // Creating an array of length l
            int a[] = new int[l];
 
            // Initializing i with the last index of array
            int i = l - 1;
 
            while (x > 0) {
 
                // Filling array from right to left
                a[i] = x % 10;
                x = x / 10;
                i--;
            }
 
            // Calculating the absolute consecutive difference
            for (int j = 0; j < l - 1; j++) {
 
                // Updating the value of n in every loop
                n = n * 10 + Math.abs(a[j] - a[j + 1]);
            }
        }
 
        // While loop ends here and we have found
        // the RSF value of N
        return n;
    }
 
    // Driver code
    public static void main(String[] arg)
    {
        int n = 6972;
 
        // Passing n to RSF function and getting answer
        int ans = RSF(n);
 
        // Printing the value stored in ans
        System.out.println(ans);
    }
}

Python3

# Python3 implementation of the approach
 
# Function to return the resultant digit
# after performing the given operations
def RSF(n):
    while (n >= 10):
 
        # Creating an extra copy of n
        x = n;
        l = 0;
 
        # Counting the number of digits in n
        while (n > 0):
            n = n // 10;
            l += 1;
 
        # Now n is 0
        # Creating an array of length l
        a = [0] * l;
 
        # Initializing i with the last index of array
        i = l - 1;
        while (x > 0):
 
            # Filling array from right to left
            a[i] = x % 10;
            x = x // 10;
            i -= 1;
 
        # Calculating the absolute
        # consecutive difference
        for j in range(0, l - 1):
 
            # Updating the value of n in every loop
            n = n * 10 + abs(a[j] - a[j + 1]);
             
    # While loop ends here and we have found
    # the RSF value of N
    return n;
 
# Driver code
if __name__ == '__main__':
    n = 614;
 
    # Passing n to RSF function
    # and getting answer
    ans = RSF(n);
 
    # Printing the value stored in ans
    print(ans);
 
# This code is contributed by Rajput-Ji

C#

// C# implementation of the approach
using System;
class GFG
{
 
// Function to return the resultant digit
// after performing the given operations
static int RSF(int n)
{
    while (n >= 10)
    {
 
        // Creating an extra copy of n
        int x = n;
        int l = 0;
 
        // Counting the number of digits in n
        while (n > 0)
        {
            n = n / 10;
            l++;
        }
 
        // Now n is 0
        // Creating an array of length l
        int []a = new int[l];
 
        // Initializing i with the last index of array
        int i = l - 1;
 
        while (x > 0)
        {
 
            // Filling array from right to left
            a[i] = x % 10;
            x = x / 10;
            i--;
        }
 
        // Calculating the absolute
        // consecutive difference
        for (int j = 0; j < l - 1; j++)
        {
 
            // Updating the value of n in every loop
            n = n * 10 + Math.Abs(a[j] - a[j + 1]);
        }
    }
 
    // While loop ends here and we have found
    // the RSF value of N
    return n;
}
 
// Driver code
public static void Main(String[] arg)
{
    int n = 6972;
 
    // Passing n to RSF function and getting answer
    int ans = RSF(n);
 
    // Printing the value stored in ans
    Console.WriteLine(ans);
}
}
 
// This code is contributed by Princi Singh

Javascript

<script>
// javascript implementation of the approach   
// Function to return the resultant digit
    // after performing the given operations
    function RSF(n) {
        while (n >= 10) {
 
            // Creating an extra copy of n
            var x = n;
            var l = 0;
 
            // Counting the number of digits in n
            while (n > 0) {
                n = parseInt(n / 10);
                l++;
            }
 
            // Now n is 0
            // Creating an array of length l
            var a = Array(l).fill(0);
 
            // Initializing i with the last index of array
            var i = l - 1;
 
            while (x > 0) {
 
                // Filling array from right to left
                a[i] = x % 10;
                x = parseInt(x / 10);
                i--;
            }
 
            // Calculating the absolute consecutive difference
            for (j = 0; j < l - 1; j++) {
 
                // Updating the value of n in every loop
                n = n * 10 + Math.abs(a[j] - a[j + 1]);
            }
        }
 
        // While loop ends here and we have found
        // the RSF value of N
        return n;
    }
 
    // Driver code
        var n = 6972;
 
        // Passing n to RSF function and getting answer
        var ans = RSF(n);
 
        // Printing the value stored in ans
        document.write(ans);
 
// This code contributed by aashish1995
</script>
Producción: 

2

 

Complejidad de tiempo : O (n logn)

Espacio Auxiliar : O(1)

Publicación traducida automáticamente

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