Dada una string M que consta de letras, dígitos y símbolos, la tarea es convertir la string en un número de móvil válido eliminando todos los caracteres excepto los dígitos en el siguiente formato:
- Forme una substring de 3 dígitos mientras que la longitud de la string restante es mayor que 3 .
- Encierre cada substring con corchetes «()» y sepárelos con «-« .
Si no se puede obtener un número de móvil válido, es decir, si la string no consta de 10 dígitos, imprima -1 . De lo contrario, imprima la string obtenida.
Ejemplos:
Entrada: M = “91 234rt5%34*0 3”
Salida: “(912)-(345)-(340)-(3)”
Explicación: Después de eliminar todos los caracteres adicionales, M = “9123453403”. Por tanto, la string final obtenida es “(912)-(345)-(340)-(3)”.Entrada: M=”9 9 ry7%64 9 7″
Salida: “No válido”
Explicación: Después de eliminar los caracteres adicionales M=”9976497″. Dado que la longitud de la string no es igual a 10, la salida requerida es -1.
Enfoque: siga los pasos a continuación para resolver el problema:
- Inicialice una string, diga S y agregue todos los dígitos de M en S en el orden dado.
- Ahora, si la longitud de S no es 10 , imprima «Inválido» y finalice el programa.
- De lo contrario, si la longitud de la string S es 10 , haga un grupo de 3 caracteres y enciérrelo entre corchetes “()” y sepárelo con “-“ .
- Imprime la string final como S .
A continuación se muestra la solución para el problema anterior.
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to print the valid // and formatted phone number void Validate(string M) { // Length of given string int len = M.size(); // Store digits in temp string temp = ""; // Iterate given M for (int i = 0; i < len; i++) { // If any digit, append it to temp if (isdigit(M[i])) temp += M[i]; } // Find new length of string int nwlen = temp.size(); // If length is not equal to 10 if (nwlen != 10) { cout << "Invalid\n"; return; } // Store final result string res = ""; // Make groups of 3 digits and // enclose them within () and // separate them with "-" // 0 to 2 index 1st group string x = temp.substr(0, 3); res += "(" + x + ")-"; // 3 to 5 index 2nd group x = temp.substr(3, 3); res += "(" + x + ")-"; // 6 to 8 index 3rd group x = temp.substr(6, 3); res += "(" + x + ")-"; // 9 to 9 index last group x = temp.substr(9, 1); res += "(" + x + ")"; // Print final result cout << res << "\n"; } // Driver Code int main() { // Given string string M = "91 234rt5%34*0 3"; // Function Call Validate(M); } // contributed by ajaykr00kj
Java
// Java program for the above approach import java.util.*; class GFG { // Function to print the valid // and formatted phone number static void Validate(String M) { // Length of given String int len = M.length(); // Store digits in temp String temp = ""; // Iterate given M for (int i = 0; i < len; i++) { // If any digit, append it to temp if (Character.isDigit(M.charAt(i))) temp += M.charAt(i); } // Find new length of String int nwlen = temp.length(); // If length is not equal to 10 if (nwlen != 10) { System.out.print("Invalid\n"); return; } // Store final result String res = ""; // Make groups of 3 digits and // enclose them within () and // separate them with "-" // 0 to 2 index 1st group String x = temp.substring(0, 3); res += "(" + x + ")-"; // 3 to 5 index 2nd group x = temp.substring(3, 6); res += "(" + x + ")-"; // 6 to 8 index 3rd group x = temp.substring(6, 9); res += "(" + x + ")-"; // 9 to 9 index last group x = temp.substring(9, 10); res += "(" + x + ")"; // Print final result System.out.print(res+ "\n"); } // Driver Code public static void main(String[] args) { // Given String String M = "91 234rt5%34*0 3"; // Function Call Validate(M); } } // This code is contributed by shikhasingrajput
Python3
# Python3 program for the above approach # Function to print valid # and formatted phone number def Validate(M): # Length of given lenn = len(M) # Store digits in temp temp = "" # Iterate given M for i in range(lenn): # If any digit:append it to temp if (M[i].isdigit()): temp += M[i] # Find new length of nwlenn = len(temp) # If length is not equal to 10 if (nwlenn != 10): print ("Invalid") return # Store final result res = "" # Make groups of 3 digits and # enclose them within () and # separate them with "-" # 0 to 2 index 1st group x = temp[0:3] res += "(" + x + ")-" # 3 to 5 index 2nd group x = temp[3 : 3 + 3] res += "(" + x + ")-" # 6 to 8 index 3rd group x = temp[6 : 3 + 6] res += "(" + x + ")-" # 9 to 9 index last group x = temp[9 : 1 + 9] res += "(" + x + ")" # Print final result print(res) # Driver Code if __name__ == '__main__': # Given M = "91 234rt5%34*0 3" # Function Call Validate(M) # This code is contributed by mohit kumar 29
C#
// C# program for the above approach using System; class GFG { // Function to print the valid // and formatted phone number static void Validate(string M) { // Length of given String int len = M.Length; // Store digits in temp string temp = ""; // Iterate given M for (int i = 0; i < len; i++) { // If any digit, append it to temp if (Char.IsDigit(M[i])) temp += M[i]; } // Find new length of String int nwlen = temp.Length; // If length is not equal to 10 if (nwlen != 10) { Console.Write("Invalid\n"); return; } // Store final result string res = ""; // Make groups of 3 digits and // enclose them within () and // separate them with "-" // 0 to 2 index 1st group string x = temp.Substring(0, 3); res += "(" + x + ")-"; // 3 to 5 index 2nd group x = temp.Substring(3, 3); res += "(" + x + ")-"; // 6 to 8 index 3rd group x = temp.Substring(6, 3); res += "(" + x + ")-"; // 9 to 9 index last group x = temp.Substring(9, 1); res += "(" + x + ")"; // Print final result Console.WriteLine(res); } // Driver Code public static void Main(string[] args) { // Given String string M = "91 234rt5%34*0 3"; // Function Call Validate(M); } } // This code is contributed by AnkThon
Javascript
<script> // JavaScript program for the above approach // Function to print the valid // and formatted phone number function Validate(M) { // Length of given String let len = M.length; // Store digits in temp let temp = ""; // Iterate given M for (let i = 0; i < len; i++) { // If any digit, append it to temp if (! isNaN( parseInt(M[i]) )) temp += M[i]; } // Find new length of String let nwlen = temp.length; // If length is not equal to 10 if (nwlen != 10) { document.write("Invalid<br>"); return; } // Store final result let res = ""; // Make groups of 3 digits and // enclose them within () and // separate them with "-" // 0 to 2 index 1st group let x = temp.substring(0, 3); res += "(" + x + ")-"; // 3 to 5 index 2nd group x = temp.substring(3, 6); res += "(" + x + ")-"; // 6 to 8 index 3rd group x = temp.substring(6, 9); res += "(" + x + ")-"; // 9 to 9 index last group x = temp.substring(9, 10); res += "(" + x + ")"; // Print final result document.write(res+ "<br>"); } // Driver Code // Given String let M = "91 234rt5%34*0 3"; // Function Call Validate(M); // This code is contributed by patel2127 </script>
(912)-(345)-(340)-(3)
Complejidad de tiempo: O(|M|+|S|)
Espacio auxiliar: O(|M|+|S|)
Publicación traducida automáticamente
Artículo escrito por ajaykr00kj y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA