Java >> Tutoriel Java >  >> Java

Nombre fascinant en Java

Dans cet article, nous développerons un programme Java pour vérifier si le nombre donné est un nombre fascinant ou non ? Nous développerons également un programme Java pour trouver tous les nombres fascinants entre deux nombres donnés.

Un nombre est appelé un nombre fascinant s'il est (ayant au moins 3 chiffres) multiplié par 2 et 3, et ces deux produits sont concaténés avec le nombre d'origine, alors le nouveau nombre contient tous les chiffres de 1 à 9 exactement une fois que. Il peut y avoir n'importe quel nombre de zéros et sont ignorés.

Exemple :-
Nombre =192
Multiplier par 2 => 192 * 2 =384
Multiplier par 3 => 192 * 3 =576
Concaténation => "192" + "384" + "576" =192384576, ce qui contient tous les chiffres de 1 à 9 exactement une fois. C'est donc un chiffre fascinant.

Puisque 192 est un nombre fascinant, 1902, 19002, 19000…0002 sont également un nombre fascinant. Parce que le nombre de 0 est ignoré.

Un autre exemple :-
Nombre =273
Multiplier par 2 => 273 * 2 =546
Multiplier par 3 => 273 * 3 =819
Concaténation => "273" + "546" + "819" ="273546819" , qui contient tous les chiffres de 1 à 9 exactement une fois. C'est donc un chiffre fascinant.

Procédure

1) Prenez un nombre
2) Déclarez une chaîne et initialisez-la avec la concaténation de nombre, nombre*2 et nombre*3. Pour la concaténation, nous pouvons utiliser l'opérateur +

String str = "" + number + number*2 + number*3;

3) Déclarez un tableau d'entiers de taille 10, par défaut tous les éléments d'un tableau sont 0
4) Parcourez les caractères de la chaîne.

  • Trouvez le ième caractère dans la ième itération
  • Convertir ce caractère en chiffre (Pas en valeur ASCII) et
  • Vérifier que le tableau[chiffre] est 0 ou non ? Si oui, augmentez la valeur de l'élément array[digit] de 1. Mais si array[digit] n'est pas 0, cela signifie déjà qu'il est augmenté en raison du même chiffre existant précédent, donc le nombre n'est pas un nombre fascinant.
If( arr[digit] == 0 ) arr[digit]++;
else return false;

5) Maintenant, vérifiez le chiffre manquant, ignorez element=0. Si un élément du tableau est zéro, cela signifie que la chaîne (nombre) ne contient pas ce nombre. Ainsi, le nombre n'est pas un nombre fascinant.
6) Si toutes les conditions précédentes sont satisfaites, alors c'est un nombre fascinant.

Programme

import java.util.Scanner;

public class FascinatingNumber {

   // Method to check the Fascinating number
   public static boolean isFascinating(int number){

      // declare variables
      int digit = 0;

      // new number
      String str = "" + number + 
                    number*2 + number*3;

      // declare an array of size 10
      int arr[] = new int[10];

      // compare array elements and
      // characters of the string
      for(int i=0; i<str.length(); i++) {

         // fetch ith character and 
         // convert it into number
         digit = str.charAt(i) - '0';

         // check arr[digit] element
         // and ignore 0
         if(digit==0 || arr[digit]==0)
            arr[digit]++;

         else return false;
      }

      // check their is any
      // missing number.
      // Ignore 1st element (0) of array
      for(int i=1; i<arr.length; i++) {

         // digit i was not their in String
         if(arr[i]==0)
            return false;
     }

      // all conditions satisfied so, return true
      return true;
   }

   // main method
   public static void main(String[] args) {

      // declare variables
      int number = 0;
      boolean result = false;

      //create Scanner class object to take input
      Scanner scan = new Scanner(System.in);

      // take input from end-user
      System.out.print("Enter an integer number::");
      number = scan.nextInt();

      // check number is Fascinating number or not
      result = isFascinating(number);

      // display
      if(result)
      System.out.println(number +
                  " is a Fascinating number.");
      else
      System.out.println(number +
                 " is not a Fascinating number.");

      // close Scanner class object
      scan.close();
   }
}

La sortie pour les différents cas de test est :-

Entrez un nombre entier ::192
192 est un nombre fascinant.

Entrez un nombre entier ::1902
1902 est un nombre fascinant.

Entrez un nombre entier ::219
219 est un nombre fascinant.

Entrez un nombre entier ::1234
1234 n'est pas un nombre fascinant.

Programme Java pour trouver tous les nombres fascinants entre deux nombres

import java.util.Scanner;

public class FascinatingNumberInRange {

   // method to check the Fascinating number
   public static boolean isFascinating(int number) {

      // declare variables
      int digit = 0;

      // new number
      String str = "" + number + number*2 + number*3;

      // declare an array of size 10
      int arr[] = new int[10];

      // compare array elements and
      // characters of the string
      for(int i=0; i<str.length(); i++) {

         // fetch ith character and 
         // convert it into number
         digit = str.charAt(i) - '0';

         // check arr[digit] element
         // and ignore 0
         if(digit==0 || arr[digit]==0)
            arr[digit]++;

         else return false;
      }

      // check their is any
      // missing number.
      // Ignore 1st element (0) of array
      for(int i=1; i<arr.length; i++) {

         // digit i was not their in String
         if(arr[i]==0)
            return false;
      }

      // all conditions satisfied so, return true
      return true;
   }

   public static void main(String[] args) {

       // declare variables
       int minRange = 0, maxRange = 0;

       //create Scanner class object to take input
       Scanner scan = new Scanner(System.in);
       System.out.print("Enter minimum value of range:");
       minRange = scan.nextInt();
       System.out.print("Enter maximum value of range:");
       maxRange = scan.nextInt();

       System.out.println("The Fascinating number from "+ 
               minRange + " to "+ maxRange+" are: ");

       // loop
       for(int i=minRange; i<=maxRange; i++) {
           // check number
           if(isFascinating(i))
               System.out.print(i +" ");
       }

       // close Scanner class object
       scan.close();
    }
}

La sortie pour les différents cas de test est :-

Entrez minimum valeur de la plage : 1
Entrez maximum valeur de la plage : 1 000
Les nombres fascinants de 1 à 1 000 sont :
192 219 273 327

Entrez minimum valeur de la plage :1000
Entrez maximum valeur de la plage :10 000
Les nombres fascinants de 1 000 à 10 000 sont :
1902 1920 2019 2190 2703 2730 3027 3270


Balise Java