Imprimir todos los números de un rango dado que se componen de dígitos consecutivos

Dado un rango [L, R] , la tarea es encontrar todos los números del rango [L, R] cuyos dígitos son consecutivos. Imprime todos esos números en orden creciente.

Ejemplos:

Entrada: L = 12, R = 34
Salida: 12 23 34

Entrada: L = 12, R = 25
Salida: 12 23

Enfoque: El problema dado se puede resolver generando todos los números posibles y almacenando todos aquellos números que satisfacen la condición dada. Después de generar todos los números, imprima todos los números almacenados en orden. Siga los pasos a continuación para resolver el problema dado:

  • Inicializa una variable, digamos num como «» que almacena la forma de string de todos los números posibles que tienen dígitos consecutivos y en orden creciente.
  • Iterar sobre el rango [1, 9] usando la variable i y realizar los siguientes pasos:
    • Actualice el número de string a la forma de string de i y si este valor se encuentra sobre el rango [L, R] , guárdelo en el vector Ans[] .
    • Itere sobre el rango [1, 9] usando la variable j , agregue la forma de carácter de j a la string num , y si la forma entera de la string num se encuentra sobre el rango [L, R] , entonces almacene esto en el vector Ans [] .
  • Después de completar los pasos anteriores, ordene el vector Ans[] para imprimir todos los números generados.

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

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the consecutive
// digit numbers in the given range
vector<int> solve(int start, int end)
{
    // Initialize num as empty string
    string num = "";
 
    // Stores the resultant number
    vector<int> ans;
 
    // Iterate over the range [1, 9]
    for (int i = 1; i <= 9; i++) {
 
        num = to_string(i);
        int value = stoi(num);
 
        // Check if the current number
        // is within range
        if (value >= start
            and value <= end) {
            ans.push_back(value);
        }
 
        // Iterate on the digits starting
        // from i
        for (int j = i + 1; j <= 9; j++) {
 
            num += to_string(j);
            value = stoi(num);
 
            // Checking the consecutive
            // digits numbers starting
            // from i and ending at j
            // is within range or not
            if (value >= start
                and value <= end) {
                ans.push_back(value);
            }
        }
    }
 
    // Sort the numbers in the
    // increasing order
    sort(ans.begin(), ans.end());
 
    return ans;
}
 
// Driver Code
int main()
{
    int L = 12, R = 87;
 
    vector<int> ans = solve(12, 87);
 
    // Print the required numbers
    for (auto& it : ans)
        cout << it << ' ';
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the consecutive
// digit numbers in the given range
static Vector<Integer> solve(int start, int end)
{
     
    // Initialize num as empty String
    String num = "";
 
    // Stores the resultant number
    Vector<Integer> ans = new Vector<>();
 
    // Iterate over the range [1, 9]
    for(int i = 1; i <= 9; i++)
    {
        num = Integer.toString(i);
        int value = i;
 
        // Check if the current number
        // is within range
        if (value >= start &&
            value <= end)
        {
            ans.add(value);
        }
 
        // Iterate on the digits starting
        // from i
        for(int j = i + 1; j <= 9; j++)
        {
            num += Integer.toString(j);
            value = Integer.valueOf(num);
 
            // Checking the consecutive
            // digits numbers starting
            // from i and ending at j
            // is within range or not
            if (value >= start &&
                value <= end)
            {
                ans.add(value);
            }
        }
    }
     
    // Sort the numbers in the
    // increasing order
    Collections.sort(ans);;
     
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int L = 12, R = 87;
     
    Vector<Integer> ans = solve(L,R);
     
    // Print the required numbers
    for(int it : ans)
        System.out.print(it + " ");
}
}
 
// This code is contributed by gauravrajput1

Python3

# Python3 program for the above approach
 
# Function to find the consecutive
# digit numbers in the given range
def solve(start, end):
    # Initialize num as empty string
    num = ""
 
    # Stores the resultant number
    ans = []
 
    # Iterate over the range [1, 9]
    for i in range(1,10,1):
        num = str(i)
        value = int(num)
 
        # Check if the current number
        # is within range
        if (value >= start and value <= end):
            ans.append(value)
 
        # Iterate on the digits starting
        # from i
        for j in range(i + 1,10,1):
            num += str(j)
            value = int(num)
 
            # Checking the consecutive
            # digits numbers starting
            # from i and ending at j
            # is within range or not
            if (value >= start and value <= end):
                ans.append(value)
 
    # Sort the numbers in the
    # increasing order
    ans.sort()
 
    return ans
 
# Driver Code
if __name__ == '__main__':
    L = 12
    R = 87
 
    ans = solve(12, 87)
 
    # Print the required numbers
    for it in ans:
        print(it,end = " ")
         
        # This code is contributed by SURENDRA_GANGWAR.

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
class Program
{
     
// Function to find the consecutive
// digit numbers in the given range
static void solve(int start, int end)
{
     
    // Initialize num as empty String
    string num = "";
 
    // Stores the resultant number
    List<int> ans = new List<int>();
 
    // Iterate over the range [1, 9]
    for(int i = 1; i <= 9; i++)
    {
        num = i.ToString();
        int value = i;
 
        // Check if the current number
        // is within range
        if (value >= start && value <= end)
        {
            ans.Add(value);
        }
 
        // Iterate on the digits starting
        // from i
        for(int j = i + 1; j <= 9; j++)
        {
            num += j.ToString();
            value = Int32.Parse(num);
 
            // Checking the consecutive
            // digits numbers starting
            // from i and ending at j
            // is within range or not
            if (value >= start &&
                value <= end)
            {
                ans.Add(value);
            }
        }
    }
     
    // Sort the numbers in the
    // increasing order
    ans.Sort();
     
    // Print the required numbers
    foreach(int it in ans)
        Console.Write(it + " ");
}
 
  // Driver code
    static void Main() {
        int L = 12, R = 87;
        solve(L,R);
    }
}
 
// This code is contributed by SoumikMondal

Javascript

<script>
// javascript program for the above approach
 
    // Function to find the consecutive
    // digit numbers in the given range
     function solve(start , end) {
 
        // Initialize num as empty String
        var num = "";
 
        // Stores the resultant number
        var ans = [];
 
        // Iterate over the range [1, 9]
        for (var i = 1; i <= 9; i++) {
            num = i.toString();
            var value = i;
 
            // Check if the current number
            // is within range
            if (value >= start && value <= end) {
                ans.push(value);
            }
 
            // Iterate on the digits starting
            // from i
            for (j = i + 1; j <= 9; j++) {
                num += j.toString();
                value = num;
 
                // Checking the consecutive
                // digits numbers starting
                // from i and ending at j
                // is within range or not
                if (value >= start && value <= end) {
                    ans.push(value);
                }
            }
        }
 
        // Sort the numbers in the
        // increasing order
        return ans;
    }
 
    // Driver Code
        var L = 12, R = 87;
        var ans = solve(L, R);
 
        // Print the required numbers
        for (it of ans)
            document.write(it + " ");
 
// This code is contributed by Rajput-Ji
</script>
Producción: 

12 23 34 45 56 67 78

 

Complejidad de tiempo: O(1)
Complejidad de espacio: O(1)

Publicación traducida automáticamente

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