Encuentra todos los números autobiográficos con un número dado de dígitos

Dado N como el número de dígitos, la tarea es encontrar todos los Números Autobiográficos cuya longitud sea igual a N. 
 

Un número autobiográfico es un número tal que el primer dígito cuenta cuántos ceros hay en él, el segundo dígito cuenta cuántos hay y así sucesivamente. 
Por ejemplo, 1210 tiene 1 cero, 2 unos, 1 dos y 0 tres. 
 

Ejemplos: 
 

Entrada: N = 4 
Salida: 1210, 2020
Entrada: N = 5 
Salida: 21200 
 

Enfoque: cualquier número con N dígitos se encuentra en el rango [10 (n-1) , 10 n -1] . Entonces, cada número en este rango se itera y verifica si es un número autobiográfico o no. 
 

  1. Convertir el número en una string
  2. iterar a través de cada dígito y almacenarlo en una variable.
  3. Luego ejecute un ciclo interno, compare el iterador del ciclo externo con cada dígito del ciclo interno y, si son iguales, incremente el recuento de ocurrencias del dígito.
  4. Luego verifique la igualdad entre el recuento de ocurrencias y la variable en la que se almacena cada dígito para que podamos saber si el número actual es autobiográfico o no.

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

C++

// C++ implementation to find
// Autobiographical numbers with length N
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return if the
// number is autobiographical or not
bool isAutoBio(int num)
{
 
    string autoStr;
 
    int index, number, i, j, cnt;
 
    // Converting the integer
    // number to string
    autoStr = to_string(num);
 
    for (int i = 0;
         i < autoStr.size();
         i++) {
 
        // Extracting each character
        // from each index one by one
        // and converting into an integer
        index = autoStr.at(i) - '0';
 
        // Initialise count as 0
        cnt = 0;
 
        for (j = 0; j < autoStr.size(); j++) {
 
            number = autoStr.at(j) - '0';
 
            // Check if it is equal to the
            // index i if true then
            // increment the count
            if (number == i)
 
                // It is an
                // Autobiographical
                // number
                cnt++;
        }
 
        // Return false if the count and
        // the index number are not equal
        if (index != cnt)
 
            return false;
    }
 
    return true;
}
 
// Function to print autobiographical number
// with given number of digits
void findAutoBios(int n)
{
 
    int high, low, i, flag = 0;
 
    // Left boundary of interval
    low = pow(10, n - 1);
 
    // Right boundary of interval
    high = pow(10, n) - 1;
 
    for (i = low; i <= high; i++) {
        if (isAutoBio(i)) {
            flag = 1;
            cout << i << ", ";
        }
    }
 
    // Flag = 0 implies that the number
    // is not an autobiographical no.
    if (!flag)
        cout << "There is no "
             << "Autobiographical number"
             << " with " << n
             << " digits\n";
}
 
// Driver Code
int main()
{
 
    int N = 0;
    findAutoBios(N);
 
    N = 4;
    findAutoBios(N);
 
    return 0;
}

Java

// Java implementation to find
// Autobiographical numbers with length N
 
import java.util.*;
import java.lang.Math;
 
public class autobio {
    public static boolean isAutoBio(int num)
    {
        String autoStr;
 
        int index, number, i, j, cnt;
 
        // Converting the integer
        // number to string
        autoStr = Integer.toString(num);
 
        for (i = 0; i < autoStr.length(); i++) {
 
            // Extracting each character
            // from each index one by one
            // and converting into an integer
            index = Integer.parseInt(autoStr.charAt(i) + "");
 
            // initialize count as 0
            cnt = 0;
 
            for (j = 0; j < autoStr.length(); j++) {
                number = Integer.parseInt(autoStr.charAt(j) + "");
 
                // Check if it is equal to the
                // index i if true then
                // increment the count
                if (number == i)
 
                    // It is an
                    // Autobiographical
                    // number
                    cnt++;
            }
 
            // Return false if the count and
            // the index number are not equal
            if (cnt != index)
 
                return false;
        }
 
        return true;
    }
 
    // Function to print autobiographical number
    // with given number of digits
    public static void findAutoBios(double n)
    {
        // both the boundaries are taken double, so as
        // to satisfy Math.pow() function's signature
        double high, low;
 
        int i, flag = 0;
 
        // Left boundary of interval
        low = Math.pow(10.0, n - 1);
 
        // Right boundary of interval
        high = Math.pow(10.0, n) - 1.0;
 
        for (i = (int)low; i <= (int)high; i++)
 
            if (isAutoBio(i)) {
                flag = 1;
                System.out.print(i + ", ");
            }
 
        // Flag = 0 implies that the number
        // is not an autobiographical no.
        if (flag == 0)
 
            System.out.println("There is no Autobiographical Number"
                               + "with " + (int)n + " digits");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        double N = 0;
        findAutoBios(N);
 
        N = 4;
        findAutoBios(N);
    }
}

Python3

# Python implementation to find
# Autobiographical numbers with length N
 
from math import pow
 
# Function to return if the
# number is autobiographical or not
def isAutoBio(num):
     
    # Converting the integer
    # number to string
    autoStr = str(num)
 
    for i in range(0, len(autoStr)):
         
 
        # Extracting each character
        # from each index one by one
        # and converting into an integer
        index = int(autoStr[i])
 
        # Initialize count as 0
        cnt = 0
 
        for j in range(0, len(autoStr)):
         
            number = int(autoStr[j])
 
            # Check if it is equal to the
            # index i if true then
            # increment the count
            if number == i:
 
                # It is an
                # Autobiographical
                # number
                cnt += 1
 
        # Return false if the count and
        # the index number are not equal
        if cnt != index:
 
            return False
     
    return True
 
# Function to print autobiographical number
# with given number of digits
def findAutoBios(n):
 
    # Left boundary of interval
    low = int(pow(10, n-1))
 
    # Right boundary of interval
    high = int(pow(10, n) - 1)
 
    flag = 0
 
    for i in range(low, high + 1):
        if isAutoBio(i):
            flag = 1
            print(i, end =', ')
 
    # Flag = 0 implies that the number
    # is not an autobiographical no.
    if flag == 0:
        print("There is no Autobiographical Number with "+ str(n) + " digits")
 
# Driver Code
if __name__ == "__main__":
 
    N = 0
    findAutoBios(N)
 
    N = 4
    findAutoBios(N)

C#

// C# implementation to find
// Autobiographical numbers with length N
using System;
  
class autobio {
    public static bool isAutoBio(int num)
    {
        String autoStr;
  
        int index, number, i, j, cnt;
  
        // Converting the integer
        // number to string
        autoStr = num.ToString();
  
        for (i = 0; i < autoStr.Length; i++) {
  
            // Extracting each character
            // from each index one by one
            // and converting into an integer
            index = Int32.Parse(autoStr[i] + "");
  
            // initialize count as 0
            cnt = 0;
  
            for (j = 0; j < autoStr.Length; j++) {
                number = Int32.Parse(autoStr[j] + "");
  
                // Check if it is equal to the
                // index i if true then
                // increment the count
                if (number == i)
  
                    // It is an
                    // Autobiographical
                    // number
                    cnt++;
            }
  
            // Return false if the count and
            // the index number are not equal
            if (cnt != index)
  
                return false;
        }
  
        return true;
    }
  
    // Function to print autobiographical number
    // with given number of digits
    public static void findAutoBios(double n)
    {
        // both the boundaries are taken double, so as
        // to satisfy Math.Pow() function's signature
        double high, low;
  
        int i, flag = 0;
  
        // Left boundary of interval
        low = Math.Pow(10.0, n - 1);
  
        // Right boundary of interval
        high = Math.Pow(10.0, n) - 1.0;
  
        for (i = (int)low; i <= (int)high; i++)
  
            if (isAutoBio(i)) {
                flag = 1;
                Console.Write(i + ", ");
            }
  
        // Flag = 0 implies that the number
        // is not an autobiographical no.
        if (flag == 0)
  
            Console.WriteLine("There is no Autobiographical Number"
                               + "with " + (int)n + " digits");
    }
  
    // Driver Code
    public static void Main(String[] args)
    {
        double N = 0;
        findAutoBios(N);
  
        N = 4;
        findAutoBios(N);
    }
}
 
// This code is contributed by sapnasingh4991

Javascript

<script>
 
// JavaScript implementation to find
// Autobiographical numbers with length N
 
// Function to return if the
// number is autobiographical or not
function isAutoBio(num){
     
    // Converting the integer
    // number to string
    let autoStr = num.toString()
 
    for(let i=0;i<autoStr.length;i++){
         
 
        // Extracting each character
        // from each index one by one
        // and converting into an integer
        let index = parseInt(autoStr[i])
 
        // Initialize count as 0
        let cnt = 0
 
        for(let j=0;j<autoStr.length;j++){
         
            let number = parseInt(autoStr[j])
 
            // Check if it is equal to the
            // index i if true then
            // increment the count
            if(number == i){
 
                // It is an
                // Autobiographical
                // number
                cnt += 1
            }
        }
 
        // Return false if the count and
        // the index number are not equal
        if(cnt != index){
 
            return false
        }
    }
     
    return true
}
 
// Function to print autobiographical number
// with given number of digits
function findAutoBios(n){
 
    // Left boundary of interval
    let low = parseInt(Math.pow(10, n-1))
 
    // Right boundary of interval
    let high = parseInt(Math.pow(10, n) - 1)
 
    let flag = 0
 
    for(let i=low;i<high+1;i++){
        if(isAutoBio(i)){
            flag = 1
            document.write(i,', ')
        }
    }
 
    // Flag = 0 implies that the number
    // is not an autobiographical no.
    if(flag == 0)
        document.write("There is no Autobiographical Number with "+ n + " digits","</br>")
}
 
// Driver Code
 
let N = 0
findAutoBios(N)
 
N = 4
findAutoBios(N)
 
// This code is contributed by shinjanpatra
 
</script>
Producción: 

There is no Autobiographical number with 0 digits
1210, 2020

 

Complejidad del tiempo: O(10 n – 10 n-1 )

Espacio Auxiliar: O(1)

Publicación traducida automáticamente

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