Un número es afortunado si todos los dígitos del número son diferentes. Cómo comprobar si un número dado da suerte o no.
Ejemplos:
Input: n = 983 Output: true All digits are different Input: n = 9838 Output: false 8 appears twice
Le recomendamos encarecidamente que minimice su navegador y que pruebe esto usted mismo primero.
La idea es recorrer cada dígito de un número dado y marcar el dígito recorrido como visitado. Dado que el número total de dígitos es 10, necesitamos una array booleana de tamaño solo 10 para marcar los dígitos visitados.
A continuación se muestra la implementación de la idea anterior.
C++
// C++ program to check if a given number is lucky #include<iostream> using namespace std; // This function returns true if n is lucky bool isLucky(int n) { // Create an array of size 10 and initialize all // elements as false. This array is used to check // if a digit is already seen or not. bool arr[10]; for (int i=0; i<10; i++) arr[i] = false; // Traverse through all digits of given number while (n > 0) { // Find the last digit int digit = n%10; // If digit is already seen, return false if (arr[digit]) return false; // Mark this digit as seen arr[digit] = true; // REmove the last digit from number n = n/10; } return true; } // Driver program to test above function. int main() { int arr[] = {1291, 897, 4566, 1232, 80, 700}; int n = sizeof(arr)/sizeof(arr[0]); for (int i=0; i<n; i++) isLucky(arr[i])? cout << arr[i] << " is Lucky \n": cout << arr[i] << " is not Lucky \n"; return 0; }
Java
// Java program to check if // a given number is lucky class GFG { // This function returns true if n is lucky static boolean isLucky(int n) { // Create an array of size 10 and initialize all // elements as false. This array is used to check // if a digit is already seen or not. boolean arr[]=new boolean[10]; for (int i = 0; i < 10; i++) arr[i] = false; // Traverse through all digits // of given number while (n > 0) { // Find the last digit int digit = n % 10; // If digit is already seen, // return false if (arr[digit]) return false; // Mark this digit as seen arr[digit] = true; // Remove the last digit from number n = n / 10; } return true; } // Driver code public static void main (String[] args) { int arr[] = {1291, 897, 4566, 1232, 80, 700}; int n = arr.length; for (int i = 0; i < n; i++) if(isLucky(arr[i])) System.out.print(arr[i] + " is Lucky \n"); else System.out.print(arr[i] + " is not Lucky \n"); } } // This code is contributed by Anant Agarwal.
Python3
# python program to check if a # given number is lucky import math # This function returns true # if n is lucky def isLucky(n): # Create an array of size 10 # and initialize all elements # as false. This array is # used to check if a digit # is already seen or not. ar = [0] * 10 # Traverse through all digits # of given number while (n > 0): #Find the last digit digit = math.floor(n % 10) # If digit is already seen, # return false if (ar[digit]): return 0 # Mark this digit as seen ar[digit] = 1 # REmove the last digit # from number n = n / 10 return 1 # Driver program to test above function. arr = [1291, 897, 4566, 1232, 80, 700] n = len(arr) for i in range(0, n): k = arr[i] if(isLucky(k)): print(k, " is Lucky ") else: print(k, " is not Lucky ") # This code is contributed by Sam007.
C#
// C# program to check if // a given number is lucky using System; class GFG { // This function returns true if // n is lucky static bool isLucky(int n) { // Create an array of size 10 // and initialize all elements // as false. This array is used // to check if a digit is // already seen or not. bool []arr = new bool[10]; for (int i = 0; i < 10; i++) arr[i] = false; // Traverse through all digits // of given number while (n > 0) { // Find the last digit int digit = n % 10; // If digit is already seen, // return false if (arr[digit]) return false; // Mark this digit as seen arr[digit] = true; // Remove the last digit // from number n = n / 10; } return true; } // Driver code public static void Main () { int []arr = {1291, 897, 4566, 1232, 80, 700}; int n = arr.Length; for (int i = 0; i < n; i++) if(isLucky(arr[i])) Console.Write(arr[i] + " is Lucky \n"); else Console.Write(arr[i] + " is not Lucky \n"); } } // This code is contributed by sam007.
PHP
<?php // PHP program to check if a given // number is lucky // This function returns true // if n is lucky function isLucky($n) { // Create an array of size 10 and // initialize all elements as false. // This array is used to check if a // digit is already seen or not. $arr = array(); for ($i = 0; $i < 10; $i++) $arr[$i] = false; // Traverse through all digits // of given number while ($n > 0) { // Find the last digit $digit = $n % 10; // If digit is already seen, // return false if ($arr[$digit]) return false; // Mark this digit as seen $arr[$digit] = true; // Remove the last digit // from number $n = (int)($n / 10); } return true; } // Driver Code $arr = array(1291, 897, 4566, 1232, 80, 700); $n = sizeof($arr); for ($i = 0; $i < $n; $i++) if(isLucky($arr[$i])) echo $arr[$i] , " is Lucky \n"; else echo $arr[$i] , " is not Lucky \n"; // This code is contributed by jit_t ?>
Javascript
<script> // Javascript program to check if a given number is lucky // This function returns true if n is lucky function isLucky(n) { // Create an array of size 10 and initialize all // elements as false. This array is used to check // if a digit is already seen or not. var arr=Array(10).fill(0); for (var i=0; i<10; i++) arr[i] = false; // Traverse through all digits of given number while (n > 0) { // Find the last digit var digit = n%10; // If digit is already seen, return false if (arr[digit]) return false; // Mark this digit as seen arr[digit] = true; // REmove the last digit from number n = parseInt(n/10); } return true; } // Driver program to test above function. var arr = [1291, 897, 4566, 1232, 80, 700] var n = arr.length; for (var i=0; i<n; i++) isLucky(arr[i])? document.write( arr[i] + " is Lucky<br>"): document.write(arr[i] + " is not Lucky<br>"); </script>
Producción:
1291 is not Lucky 897 is Lucky 4566 is not Lucky 1232 is not Lucky 80 is Lucky 700 is not Lucky
Complejidad de tiempo: O(d) donde d es un número de dígitos en el número de entrada.
Espacio auxiliar: O(1)
Este artículo es una contribución de Himanshu . Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
Método 2: (usando STL y clasificación)
En este método, primero convertiremos el número en una string. Luego ordenaremos toda la string. Luego compararemos cada elemento de índice con el siguiente elemento de índice. Si ambos son iguales, detendremos esa posición e imprimiremos que el número dado no es afortunado.
Y si no obtenemos ningún índice como se discutió anteriormente, imprimiremos que el número dado es afortunado.
Toda esta tarea se completará en tiempo O(K), donde K es el número total de dígitos de N.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ code to check is the number // lucky or not. #include <bits/stdc++.h> using namespace std; void checklucky(string s,int n) { bool x = false; // traversing the whole string for (int i = 0; i < s.length() - 1; i++) { // checking next element whether // it is equal or not if (s[i] == s[i + 1]) { cout << n << " is not lucky number"<<endl; x = true; break; } } if (!x) { cout << n << " is lucky number"<<endl; } } int main() { int n1 = 1234,n2=5868; // converting the number from // integer to string using // C++ STL function. string s1 = to_string(n1); string s2 = to_string(n2); // sorting the string sort(s1.begin(), s1.end()); sort(s2.begin(), s2.end()); //function calling checklucky(s1,n1); checklucky(s2,n2); return 0; } //this code is contribut by Machhaliya Muhammad
Python3
# Python3 code to check is the number # lucky or not. def checklucky(s, n): x = False # traversing the whole string for i in range(len(s) - 1): # checking next element whether # it is equal or not if (s[i] == s[i + 1]): print(n, "is not a lucky number") return if not x: print(n, "is a lucky number") # Driver Code n1 = 1234 n2 = 5868 # converting the number from # integer to string s1 = str(n1) s2 = str(n2) # sorting the string s1 = "".join(sorted(s1)) s2 = "".join(sorted(s2)) # function calling checklucky(s1, n1) checklucky(s2, n2) # this code is contribut by phasing17
Javascript
// JavaScript code to check is the number // lucky or not. function checklucky(s, n) { let x = false; // traversing the whole string for (var i = 0; i < s.length - 1; i++) { // checking next element whether // it is equal or not if (s[i] == s[i + 1]) { console.log(n + " is not lucky number"); x = true; break; } } if (!x) { console.log(n + " is lucky number"); } } let n1 = 1234,n2=5868; // converting the number from // integer to string let s1 = n1.toString(); let s2 = n2.toString(); // sorting the string s1 = s1.split(""); s2 = s2.split(""); s1.sort(); s2.sort(); s1 = s1.join(""); s2 = s2.join(""); // function calling checklucky(s1,n1); checklucky(s2,n2); // this code is contribut by phasing17
1234 is lucky number 5868 is not lucky number
Complejidad de tiempo: O(n1*logn1 + n2*logn2), donde n1 y n2 representan las longitudes de las strings dadas.
Espacio auxiliar: O(1), no se requiere espacio adicional, por lo que es una constante.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA