Dado un String ph[] , la tarea es encontrar un nuevo número para el usuario, según las siguientes condiciones:
- El nuevo número también comenzará desde el mismo dígito que el número original.
- Los dígitos del nuevo número serán los primeros dígitos de una serie de arreglos de diferencias absolutas de los elementos consecutivos.
Ejemplos:
Entrada: ph = “9827218706”
Salida: 9154301011
Explicación:Entrada: ph =”9647253846″
Salida: 9310100011
Enfoque: Considere los siguientes pasos para resolver este problema:
- Convierta cada carácter de la string en un número entero y guárdelo en la array ph1[] usando la comprensión de listas.
- Declare una string vacía ph2 .
- Convierta el primer elemento de la array ph1[ ] en una string y agréguelo a ph2 .
- Usando la comprensión de listas, cree una array almacenando la diferencia absoluta de elementos consecutivos.
- Asigne esta array a ph1 .
- Repita los pasos 3-5, diez veces ya que el número de teléfono tiene diez dígitos.
A continuación se muestra la implementación del enfoque anterior.
Java
// Java program for above approach public class Mobile { // Function to find lucky phone number static String phone(String ph, int n) { // Converting char to int and storing into array. int[] ph1 = new int[n]; for (int i = 0; i < n; i++) ph1[i] = ph.charAt(i) - '0'; // Empty string to store lucky number. String ph2 = ""; // Loop for performing action // and adding digit to ph2. for (int i = 0; i < n; i++) { // Convert first element into // string and adding to ph2. ph2 += ph1[0]; // Creating new ph1 by subtracting // consecutive element. int ph3[] = new int[ph1.length - 1]; for (int j = 0; j < ph1.length - 1; j++) ph3[j] = Math.abs(ph1[j] - ph1[j + 1]); ph1 = ph3; } // Return lucky number ph2 return ph2; } // Driver code public static void main(String[] args) { // Original number String ph = "9827218706"; // Calling phone function. String num = phone(ph, ph.length()); // Print the lucky number System.out.println(num); } } // This code is contributed by Lovely Jain
Python3
# Function to find lucky phone number def phone(ph, n): # Converting char to int and storing into array. ph1 = [int(i) for i in ph] # Empty string to store lucky number. ph2 = "" # Loop for performing action # and adding digit to ph2. for _ in range(n): # Convert first element into # string and adding to ph2. ph2 += str(ph1[0]) # Creating new ph1 by subtracting # consecutive element. ph1 = [abs(ph1[j]-ph1[j + 1]) \ for j in range(len(ph1)-1)] # Return lucky number ph2 return ph2 # Original number ph = "9827218706" # Calling phone function. num = phone(ph, len(ph)) # Print the lucky number print(num)
Javascript
<script> // Function to find lucky phone number function phone(ph, n) { // Converting char to int and storing into array. let ph1 = []; for (i of ph) ph1.push(i) // Empty string to store lucky number. let ph2 = "" // Loop for performing action // and adding digit to ph2. for (let _ = 0; _ < n; _++) { // Convert first element into // string and adding to ph2. ph2 += new String(ph1[0]) // Creating new ph1 by subtracting // consecutive element. let temp = [] for (let j = 0; j < ph1.length - 1; j++) { temp.push(Math.abs(ph1[j] - ph1[j + 1])) } ph1 = temp } // Return lucky number ph2 return ph2 } // Original number let ph = "9827218706" // Calling phone function. let num = phone(ph, ph.length) // Print the lucky number document.write(num) // This code is contributed by gfgking. </script>
9154301011
Complejidad temporal: O(N*N)
Espacio auxiliar: O(N)
Enfoque eficiente: en este enfoque, no se requiere espacio adicional para almacenar elementos en la array. Primero, declare una string vacía ph2 en la que se almacenará el número de la suerte, ahora cree un ciclo for en el que el primer carácter de la string se agregará a ph2 y nuevamente otro ciclo for para encontrar la diferencia absoluta del elemento consecutivo. Ahora la string de diferencia absoluta se le asignará a ph1 que es el número original y se seguirán los mismos pasos. Siga los pasos a continuación para resolver el problema:
- Inicialice una variable de string ph2[] como una string vacía.
- Itere sobre el rango [0, N) usando la variable i y realice las siguientes tareas:
- Agregue ph[0] a la variable ph2[].
- Inicialice una variable de string S[] como una string vacía.
- Itere sobre el rango [0, N-1) usando la variable j y realice las siguientes tareas:
- Agregue el valor de str(abs(int(ph[j])-int(ph[j+1]))) a la variable S[].
- Establezca el valor de ph como S[].
- Después de realizar los pasos anteriores, imprima el valor de ph2[] como respuesta.
A continuación se muestra la implementación del enfoque anterior.
C++
// C++ code for the above approach #include <bits/stdc++.h> using namespace std; // Function to find lucky number. string phone(string ph, int n) { // ph2 is empty string to store lucky number. string ph2 = ""; // For loop for finding lucky number for (int i = 0; i < ph.length(); i++) { // Add first element of ph to ph2 ph2 += ph[0]; // S for storing the difference string S = ""; // Loop to calculate the absolute difference for (int j = 0; j < ph.length(); j++) { int x = abs(int(ph[j]) - int(ph[j + 1])); S += x + '0'; } // Assigning S to ph. ph = S; } // Return the lucky number return ph2; } // Driver Code int main() { // Original number string ph = "9827218706"; // Call phone function string num = phone(ph, ph.length()); // Printing lucky number cout << (num); } // This code is contributed by Potta Lokesh
Java
// Java program for the above approach import java.util.*; class GFG { // Function to find lucky number. static String phone(String ph, int n) { // ph2 is empty string to store lucky number. String ph2 = ""; // For loop for finding lucky number for (int i = 0; i < ph.length(); i++) { // Add first element of ph to ph2 ph2 += ph.charAt(0); // S for storing the difference String S = ""; // Loop to calculate the absolute difference for (int j = 0; j < ph.length()-1; j++) { int x = Math.abs(ph.charAt(j) - ph.charAt(j+1)); S += (char)(x + '0'); } // Assigning S to ph. ph = S; } // Return the lucky number return ph2; } // Driver Code public static void main(String args[]) { // Original number String ph = "9827218706"; // Call phone function String num = phone(ph, ph.length()); // Printing lucky number System.out.println(num); } } // This code is contributed by avijitmondal1998
Python3
# Function to find lucky number. def phone(ph, n): # ph2 is empty string to store lucky number. ph2 = "" # For loop for finding lucky number for i in range(len(ph)): # Add first element of ph to ph2 ph2 += ph[0] # S for storing the difference S = "" # Loop to calculate the absolute difference for j in range(len(ph)-1): x = abs(int(ph[j])-int(ph[j + 1])) S += str(x) # Assigning S to ph. ph = S # Return the lucky number return ph2 # Original number ph = "9827218706" # Call phone function num = phone(ph, len(ph)) # Printing lucky number print(num)
C#
// C# code for the above approach using System; class GFG { // Function to find lucky number. static string phone(string ph, int n) { // ph2 is empty string to store lucky number. string ph2 = ""; // For loop for finding lucky number for (int i = 0; i < ph.Length; i++) { // Add first element of ph to ph2 ph2 += ph[0]; // S for storing the difference string S = ""; // Loop to calculate the absolute difference for (int j = 0; j < ph.Length; j++) { int x = Math.Abs(ph[j] - ph[j + 1]); S += x + '0'; } // Assigning S to ph. ph = S; } // Return the lucky number return ph2; } // Driver Code public static void Main() { // Original number string ph = "9827218706"; // Call phone function string num = phone(ph, ph.Length); // Printing lucky number Console.WriteLine (num); } } // This code is contributed by ukasp.
Javascript
<script> // javascript program for the above approach // Function to find lucky number. function phone( ph , n) { // ph2 is empty string to store lucky number. // Converting char to int and storing into array. let ph1 = []; for (i of ph) ph1.push(i) // Empty string to store lucky number. let ph2 = "" // Loop for performing action // and adding digit to ph2. for (let _ = 0; _ < n; _++) { // Convert first element into // string and adding to ph2. ph2 += new String(ph1[0]) // Creating new ph1 by subtracting // consecutive element. let S = [] for (let j = 0; j < ph1.length - 1; j++) { S.push(Math.abs(ph1[j] - ph1[j + 1])) } ph1 = S } // Return the lucky number return ph2; } // Driver Code // Original number var ph = "9827218706"; // Call phone function var num = phone(ph, ph.length); // Printing lucky number document.write(num); // This code is contributed by umadevi9616 </script>
9154301011
Complejidad temporal: O(N*N)
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por harshdeepmahajan88 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA