Cree un nuevo número de móvil seleccionando el máximo de los extremos después de insertar la diferencia absoluta por pares en el medio

Dado un String ph[] , la tarea es encontrar la diferencia absoluta de elementos consecutivos e insertar el resultado entre los elementos consecutivos. Al hacer esto, el tamaño de los números de teléfono aumentará de 10 a 19 . Ahora tenemos que comparar dígitos desde el primero hasta el último y seleccionar el máximo de esta manera obtendremos un nuevo número de teléfono.

Ejemplos:

Entrada: ph = “9647253846”
Salida: 9364857553
Explicación:

Entrada: ph = “7635892563”
Salida: 7363535791

Enfoque: la idea es usar el enfoque de dos punteros para resolver este problema junto con el uso de una variable de string para agregar los números de teléfono con una diferencia. Siga los pasos a continuación para resolver el problema:

  • Inicialice una variable de string S[] como una string vacía.
  • Itere sobre el rango [0, N-1) usando la variable i y realice las siguientes tareas:
    • Agregue ph[i] a la variable S.
    • Inicialice las variables s como int(ph[i]) – int(ph[i+1]) y x como abs(s).
    • Agregue str(x) a la variable S.
  • Agregue ph[9] a la variable S.
  • Inicialice las variables s como 0 ye como len (S)-1.
  • Inicialice una variable de string ph2[] como una string vacía.
  • Atraviese un ciclo while hasta que s no sea igual a e y realice las siguientes tareas:
    • Agregue el máximo de S[s] o S[e] a la variable ph2[].
    • Aumente el valor de s en 1 y disminuya el valor de e en 1.
  • Agregue S[e] a la variable ph2[].
  • 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++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to create the phone number
string phNumber(string ph, int n)
{
 
    // Empty string to store extended number
    string S = "";
 
    // Loop for extend phone number
    for (int i = 0; i < n - 1; i++) {
 
        // Add character form string
        S += ph[i];
 
        // Finding absolute difference
        int x = abs(ph[i] - ph[i + 1]);
 
        // Adding the difference to S
        S += to_string(x);
    }
    // Adding last digit of ph
    S += ph[9];
 
    // Using 2 pointer algorithm to form comparison
 
    // s is start index
    int s = 0;
 
    // e is end index
    int e = S.length() - 1;
 
    // ph2 an empty string for
    // storing  the phone number
    string ph2 = "";
 
    // Loop till e become equal to s
    while (s != e) {
 
        // Comparing element at s and e
        // index and adding maximum
 
        if (S[s] > S[e]) {
            ph2 += S[s];
        }
        else {
            ph2 += S[e];
        }
        // Increment start index
        s += 1;
 
        // Decrement end index
        e -= 1;
    }
    // When s = e loop will terminate
    // so adding element at index s = e
    ph2 += S[e];
    // Return phone number
    return ph2;
}
 
// Driver Code
int main()
{
   
    // Original phone number
    string ph = "9647253846";
 
    // Calling function to create new number
    string num = phNumber(ph, ph.length());
 
    // Print the new number
    cout << num;
}
 
// This code is contributed by Samim Hossain Mondal.

Java

// Java program for the above approach
class GFG {
 
  // Function to create the phone number
  static String phNumber(String ph, int n) {
 
    // Empty string to store extended number
    String S = "";
 
    // Loop for extend phone number
    for (int i = 0; i < n - 1; i++) {
 
      // Add character form string
      S += ph.charAt(i);
 
      // Finding absolute difference
      int x = Math.abs(ph.charAt(i) - ph.charAt(i + 1));
 
      // Adding the difference to S
      S += Integer.toString(x);
    }
    // Adding last digit of ph
    S += ph.charAt(9);
 
    // Using 2 pointer algorithm to form comparison
 
    // s is start index
    int s = 0;
 
    // e is end index
    int e = S.length() - 1;
 
    // ph2 an empty string for
    // storing the phone number
    String ph2 = "";
 
    // Loop till e become equal to s
    while (s != e) {
 
      // Comparing element at s and e
      // index and adding maximum
 
      if (S.charAt(s) > S.charAt(e)) {
        ph2 += S.charAt(s);
      } else {
        ph2 += S.charAt(e);
      }
      // Increment start index
      s += 1;
 
      // Decrement end index
      e -= 1;
    }
    // When s = e loop will terminate
    // so adding element at index s = e
    ph2 += S.charAt(e);
    // Return phone number
    return ph2;
  }
 
  // Driver Code
  public static void main(String args[]) {
 
    // Original phone number
    String ph = "9647253846";
 
    // Calling function to create new number
    String num = phNumber(ph, ph.length());
 
    // Print the new number
    System.out.println(num);
  }
}
 
// This code is contributed by gfgking

Python3

# Function to create the phone number
def phNumber(ph, n):
   
    # Empty string to store extended number
    S =""
     
    # Loop for extend phone number
    for i in range(n-1):
       
          # Add character form string
        S+= ph[i]
         
        # Finding absolute difference
        s = int(ph[i])-int(ph[i + 1])
        x = abs(s)
         
        # Adding the difference to S
        S+= str(x)
     
    # Adding last digit of ph
    S+= ph[9]
 
    # Using 2 pointer algorithm to form comparison
     
    # s is start index
    s = 0
     
    # e is end index
    e = len(S)-1
     
    # ph2 an empty string for
    # storing the phone number
    ph2 =""
     
    # Loop till e become equal to s
    while s != e:
         
        # Comparing element at s and e
        # index and adding maximum
        ph2+= max(S[s], S[e])
         
        # Increment start index
        s+= 1
         
        # Decrement end index
        e-= 1
         
    # When s = e loop will terminate
    # so adding element at index s = e
    ph2+= S[e]
 
    # Return phone number
    return ph2
   
# Original phone number
ph = "9647253846"
 
# Calling function to create new number
num = phNumber(ph, len(ph))
 
# Print the new number
print(num)

C#

// C# program for the above approach
using System;
 
class GFG {
 
  // Function to create the phone number
  static string phNumber(string ph, int n)
  {
 
    // Empty string to store extended number
    string S = "";
 
    // Loop for extend phone number
    for (int i = 0; i < n - 1; i++) {
 
      // Add character form string
      S += ph[i];
 
      // Finding absolute difference
      int x = Math.Abs(ph[i] - ph[i + 1]);
 
      // Adding the difference to S
      S += x.ToString();
    }
    // Adding last digit of ph
    S += ph[9];
 
    // Using 2 pointer algorithm to form comparison
 
    // s is start index
    int s = 0;
 
    // e is end index
    int e = S.Length - 1;
 
    // ph2 an empty string for
    // storing the phone number
    string ph2 = "";
 
    // Loop till e become equal to s
    while (s != e) {
 
      // Comparing element at s and e
      // index and adding maximum
 
      if (S[s] > S[e]) {
        ph2 += S[s];
      }
      else {
        ph2 += S[e];
      }
      // Increment start index
      s += 1;
 
      // Decrement end index
      e -= 1;
    }
    // When s = e loop will terminate
    // so adding element at index s = e
    ph2 += S[e];
    // Return phone number
    return ph2;
  }
 
  // Driver Code
  public static void Main()
  {
 
    // Original phone number
    string ph = "9647253846";
 
    // Calling function to create new number
    string num = phNumber(ph, ph.Length);
 
    // Print the new number
    Console.Write(num);
  }
}
 
// This code is contributed by ukasp.

Javascript

<script>
       // JavaScript code for the above approach
 
       // Function to create the phone number
       function phNumber(ph, n) {
 
           // Empty string to store extended number
           let S = ""
 
           // Loop for extend phone number
           for (let i = 0; i < n - 1; i++) {
 
               // Add character form string
               S += ph[i]
 
               // Finding absolute difference
               let s = ph[i].charCodeAt(0) - ph[i + 1].charCodeAt(0)
               let x = Math.abs(s)
 
               // Adding the difference to S
               S += x.toString();
           }
           // Adding last digit of ph
           S += ph[9]
 
           // Using 2 pointer algorithm to form comparison
 
           // s is start index
           s = 0
 
           // e is end index
           e = S.length - 1
 
           // ph2 an empty string for
           // storing the phone number
           ph2 = ""
 
           // Loop till e become equal to s
           while (s != e) {
 
               // Comparing element at s and e
               // index and adding maximum
 
               if (S[s].charCodeAt(0) > S[e].charCodeAt(0)) {
                   ph2 += S[s];
               }
               else {
                   ph2 += S[e];
               }
               // Increment start index
               s += 1
 
               // Decrement end index
               e -= 1
 
 
           }
           // When s = e loop will terminate
           // so adding element at index s = e
           ph2 += S[e]
           // Return phone number
           return ph2
       }
       // Original phone number
       let ph = "9647253846"
 
       // Calling function to create new number
       let num = phNumber(ph, ph.length)
 
       // Print the new number
       document.write(num)
 
 // This code is contributed by Potta Lokesh
   </script>
Producción

9364857553

Complejidad temporal: O(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

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *