N-ésimo número positivo cuya diferencia absoluta de dígitos adyacentes es como máximo 1

Dado un número N , la tarea es encontrar el número N que tiene una diferencia absoluta de 1 entre cada par de dígitos adyacentes. Ejemplos:
 
 

Entrada: N = 5 
Salida:
Explicación: 
Los primeros 5 números son 1,2,3,4 y 5 .
Entrada: N = 15 
Salida: 23 
Explicación: 
Los primeros 15 números son 1,2,3,4,5,6,7,8,9,10,11,12,21,22 y 23
 

Enfoque: para resolver este problema, estamos utilizando la estructura de datos  Queue .
 

  • Prepare una cola vacía y ponga en cola todos los números enteros del 1 al 9 en orden creciente. 
     
  • Ahora realiza la siguiente operación N veces. 
    • Saque de la cola y almacene en el arreglo arr que almacena el número iésimo del tipo requerido en arr[i].
    • Si (arr[i] % 10 != 0), entonces poner en cola 10 * arr[i] + (arr[i] % 10) – 1 .
    • Poner en cola 10 * arr[i] + (arr[i] % 10) .
    • Si (arr[i] % 10 != 9), entonces poner en cola 10 * arr[i] + (arr[i] % 10) + 1 .
  • Devuelve arr[N] como respuesta.

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

C++

// C++ Program to find Nth number with
// absolute difference between all
// adjacent digits at most 1.
 
#include <bits/stdc++.h>
using namespace std;
 
 
// Return Nth number with
// absolute difference between all
// adjacent digits at most 1.
void findNthNumber(int N)
{
    // To store all such numbers
    long long arr[N + 1];
     
    queue<long long> q;
 
    // Enqueue all integers from 1 to 9
    // in increasing order.
    for (int i = 1; i <= 9; i++)
        q.push(i);
 
    // Perform the operation N times so that
    // we can get all such N numbers.
    for (int i = 1; i <= N; i++) {
 
        // Store the front element of queue,
        // in array and pop it from queue.
        arr[i] = q.front();
        q.pop();
 
        // If the last digit of dequeued integer is
        // not 0, then enqueue the next such number.
        if (arr[i] % 10 != 0)
            q.push(arr[i] * 10 + arr[i] % 10 - 1);
 
        // Enqueue the next such number
        q.push(arr[i] * 10 + arr[i] % 10);
 
        // If the last digit of dequeued integer is
        // not 9, then enqueue the next such number.
        if (arr[i] % 10 != 9)
            q.push(arr[i] * 10 + arr[i] % 10 + 1);
    }
     
    cout<<arr[N]<<endl;
}
 
// Driver Code
int main()
{
    int N = 21;
    findNthNumber(N);
    return 0;
}

Java

// Java program to find Nth number with
// absolute difference between all
// adjacent digits at most 1.
import java.util.*;
 
class GFG{
 
// Return Nth number with
// absolute difference between all
// adjacent digits at most 1.
static void findNthNumber(int N)
{
     
    // To store all such numbers
    int []arr = new int[N + 1];
     
    Queue<Integer> q = new LinkedList<>();
 
    // Enqueue all integers from 1 to 9
    // in increasing order.
    for(int i = 1; i <= 9; i++)
       q.add(i);
 
    // Perform the operation N times so
    // that we can get all such N numbers.
    for(int i = 1; i <= N; i++)
    {
        
       // Store the front element of queue,
       // in array and pop it from queue.
       arr[i] = q.peek();
       q.remove();
        
       // If the last digit of dequeued
       // integer is not 0, then enqueue
       // the next such number.
       if (arr[i] % 10 != 0)
           q.add(arr[i] * 10 + arr[i] % 10 - 1);
        
       // Enqueue the next such number
       q.add(arr[i] * 10 + arr[i] % 10);
        
       // If the last digit of dequeued
       // integer is not 9, then enqueue
       // the next such number.
       if (arr[i] % 10 != 9)
           q.add(arr[i] * 10 + arr[i] % 10 + 1);
    }
    System.out.println(arr[N]);
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 21;
     
    findNthNumber(N);
}
}
 
// This code is contributed by Amit Katiyar

Python3

# Python 3 Program to find Nth number with
# absolute difference between all
# adjacent digits at most 1.
 
# Return Nth number with
# absolute difference between all
# adjacent digits at most 1.
def findNthNumber(N):
     
    # To store all such numbers
    arr = [0 for i in range(N + 1)]
     
    q = []
 
    # Enqueue all integers from 1 to 9
    # in increasing order.
    for i in range(1, 10, 1):
        q.append(i)
 
    # Perform the operation N times so that
    # we can get all such N numbers.
    for i in range(1, N+1, 1):
         
        # Store the front element of queue,
        # in array and pop it from queue.
        arr[i] = q[0]
        q.remove(q[0])
 
        # If the last digit of dequeued integer is
        # not 0, then enqueue the next such number.
        if (arr[i] % 10 != 0):
            q.append(arr[i] * 10 + arr[i] % 10 - 1)
 
        # Enqueue the next such number
        q.append(arr[i] * 10 + arr[i] % 10)
 
        # If the last digit of dequeued integer is
        # not 9, then enqueue the next such number.
        if (arr[i] % 10 != 9):
            q.append(arr[i] * 10 + arr[i] % 10 + 1)
     
    print(arr[N])
 
# Driver Code
if __name__ == '__main__':
     
    N = 21
    findNthNumber(N)
 
# This code is contributed by Samarth

C#

// C# program to find Nth number with
// absolute difference between all
// adjacent digits at most 1.
using System;
using System.Collections.Generic;
 
class GFG{
 
// Return Nth number with
// absolute difference between all
// adjacent digits at most 1.
static void findNthNumber(int N)
{
     
    // To store all such numbers
    int []arr = new int[N + 1];
     
    Queue<int> q = new Queue<int>();
 
    // Enqueue all integers from 1 to 9
    // in increasing order.
    for(int i = 1; i <= 9; i++)
       q.Enqueue(i);
 
    // Perform the operation N times so
    // that we can get all such N numbers.
    for(int i = 1; i <= N; i++)
    {
        
       // Store the front element of queue,
       // in array and pop it from queue.
       arr[i] = q.Peek();
       q.Dequeue();
        
       // If the last digit of dequeued
       // integer is not 0, then enqueue
       // the next such number.
       if (arr[i] % 10 != 0)
           q.Enqueue(arr[i] * 10 +
                     arr[i] % 10 - 1);
        
       // Enqueue the next such number
       q.Enqueue(arr[i] * 10 + arr[i] % 10);
        
       // If the last digit of dequeued
       // integer is not 9, then enqueue
       // the next such number.
       if (arr[i] % 10 != 9)
           q.Enqueue(arr[i] * 10 +
                     arr[i] % 10 + 1);
    }
    Console.WriteLine(arr[N]);
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 21;
     
    findNthNumber(N);
}
}
 
// This code is contributed by Rohit_ranjan

Javascript

<script>
 
    // JavaScript program to find Nth number with
    // absolute difference between all
    // adjacent digits at most 1.
     
    // Return Nth number with
    // absolute difference between all
    // adjacent digits at most 1.
    function findNthNumber(N)
    {
 
        // To store all such numbers
        let arr = new Array(N + 1);
 
        let q = [];
 
        // Enqueue all integers from 1 to 9
        // in increasing order.
        for(let i = 1; i <= 9; i++)
           q.push(i);
 
        // Perform the operation N times so
        // that we can get all such N numbers.
        for(let i = 1; i <= N; i++)
        {
 
           // Store the front element of queue,
           // in array and pop it from queue.
           arr[i] = q[0];
           q.shift();
 
           // If the last digit of dequeued
           // integer is not 0, then enqueue
           // the next such number.
           if (arr[i] % 10 != 0)
               q.push(arr[i] * 10 + arr[i] % 10 - 1);
 
           // Enqueue the next such number
           q.push(arr[i] * 10 + arr[i] % 10);
 
           // If the last digit of dequeued
           // integer is not 9, then enqueue
           // the next such number.
           if (arr[i] % 10 != 9)
               q.push(arr[i] * 10 + arr[i] % 10 + 1);
        }
        document.write(arr[N] + "</br>");
    }
     
    let N = 21;
      
    findNthNumber(N);
 
</script>
Producción: 

45

 

Complejidad de tiempo: O(N)

Espacio Auxiliar: O(N)

Publicación traducida automáticamente

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