Programa para insertar guiones entre dos dígitos impares adyacentes en un número dado

Dado un gran número en forma de string N , la tarea es insertar un guión entre dos dígitos impares adyacentes en el número dado en forma de strings.

Ejemplos:

Entrada: N = 1745389 
Salida: 1-745-389 
Explicación: 
En la string str, str[0] y str[1] son ​​números impares consecutivos, así que inserte un guión entre ellos.
Entrada: N = 34657323128437 
Salida: 3465-7-323-12843-7

Enfoque bit a bit:

  1. Recorre toda la string de números carácter por carácter.
  2. Compare todos los caracteres consecutivos utilizando los operadores lógicos Bitwise OR y AND .
  3. Si dos caracteres consecutivos de la string son impares, inserte un guión (-) en ellos y busque los siguientes dos caracteres consecutivos.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
#include <iostream>
#include <string>
using namespace std;
 
// Function to check if char ch is
// odd or not
bool checkOdd(char ch)
{
    return ((ch - '0') & 1);
}
 
// Function to insert dash - between
// any 2 consecutive digit in string str
string Insert_dash(string num_str)
{
 
    string result_str = num_str;
 
    // Traverse the string character
    // by character
    for (int x = 0;
         x < num_str.length() - 1; x++) {
 
        // Compare every consecutive
        // character with the odd value
        if (checkOdd(num_str[x])
            && checkOdd(num_str[x + 1])) {
 
            result_str.insert(x + 1, "-");
            num_str = result_str;
            x++;
        }
    }
 
    // Print the resultant string
    return result_str;
}
 
// Driver Code
int main()
{
 
    // Given number in form of string
    string str = "1745389";
 
    // Function Call
    cout << Insert_dash(str);
 
    return 0;
}

Java

// Java program to implement
// the above approach
class GFG{
 
// Function to check if char ch is
// odd or not
static boolean checkOdd(char ch)
{
    return ((ch - '0') & 1) != 0 ?
            true : false;
}
 
// Function to insert dash - between
// any 2 consecutive digit in string str
static String Insert_dash(String num_str)
{
    StringBuilder result_str = new StringBuilder(num_str);
 
    // Traverse the string character
    // by character
    for(int x = 0; x < num_str.length() - 1; x++)
    {
 
        // Compare every consecutive
        // character with the odd value
        if (checkOdd(num_str.charAt(x)) &&
            checkOdd(num_str.charAt(x + 1)))
        {
            result_str.insert(x + 1, "-");
            num_str = result_str.toString();
            x++;
        }
    }
 
    // Print the resultant string
    return result_str.toString();
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given number in form of string
    String str = "1745389";
 
    // Function call
    System.out.println(Insert_dash(str));
}
}
 
// This code is contributed by rutvik_56

Python3

# Python3 program for the above approach
 
# Function to check if char ch is
# odd or not
def checkOdd(ch):
 
    return ((ord(ch) - 48) & 1)
 
# Function to insert dash - between
# any 2 consecutive digit in string str
def Insert_dash(num_str):
 
    result_str = num_str
 
    # Traverse the string character
    # by character
    x = 0
    while(x < len(num_str) - 1):
 
        # Compare every consecutive
        # character with the odd value
        if (checkOdd(num_str[x]) and
            checkOdd(num_str[x + 1])):
 
            result_str = (result_str[:x + 1] + '-' +
                          result_str[x + 1:])
            num_str = result_str
            x += 1
        x += 1
 
    # Print the resultant string
    return result_str
 
# Driver Code
 
# Given number in form of string
str = "1745389"
 
# Function call
print(Insert_dash(str))
 
# This code is contributed by vishu2908

C#

// C# program to implement
// the above approach
using System;
using System.Text;
class GFG{
 
// Function to check if char ch is
// odd or not
static bool checkOdd(char ch)
{
    return ((ch - '0') & 1) != 0 ?
            true : false;
}
 
// Function to insert dash - between
// any 2 consecutive digit in string str
static String Insert_dash(String num_str)
{
    StringBuilder result_str = new StringBuilder(num_str);
 
    // Traverse the string character
    // by character
    for(int x = 0; x < num_str.Length - 1; x++)
    {
 
        // Compare every consecutive
        // character with the odd value
        if (checkOdd(num_str[x]) &&
            checkOdd(num_str[x + 1]))
        {
            result_str.Insert(x + 1, "-");
            num_str = result_str.ToString();
            x++;
        }
    }
 
    // Print the resultant string
    return result_str.ToString();
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given number in form of string
    String str = "1745389";
 
    // Function call
    Console.WriteLine(Insert_dash(str));
}
}
 
// This code is contributed by Rajput-Ji
Producción: 

1-745-389

 

Complejidad temporal: O(N) 
Espacio auxiliar: O(1)
 

Enfoque de expresión regular:

El problema dado se puede resolver usando Regular Expression . El RE para este problema será: 
 

(?<=[13579])(?=[13579])
El RE dado coincide entre números impares. Podemos reemplazar la parte coincidente de ancho cero con un guión, es decir,
str = str.replaceAll(“(?<=[13579])(?=[13579])”, “-“);

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ Program to implement
// the above approach
#include <iostream>
#include <regex>
using namespace std;
 
 
// Function to insert dash - between
// any 2 consecutive odd digit
string Insert_dash(string str)
{
   
  // Get the regex to be checked
  const regex pattern("([13579])([13579])");
 
  // Replaces the matched value
  // (here dash) with given string
  return regex_replace(str, pattern, "$1-$2");;
}
 
// Driver Code
int main()
{
  string str = "1745389";
  cout << Insert_dash(str);
  return 0;
}
 
// This code is contributed by yuvraj_chandra

Java

// Java program for the above approach
 
import java.util.regex.*;
 
public class GFG {
 
    // Function to insert dash - between
    // any 2 consecutive odd digit
    public static String Insert_dash(String str)
    {
 
        // Get the regex to be checked
        String regex = "(?<=[13579])(?=[13579])";
 
        // Create a pattern from regex
        Pattern pattern = Pattern.compile(regex);
 
        // Create a matcher for the input String
        Matcher matcher
            = pattern.matcher(str);
 
        // Get the String to be replaced,
        // i.e. here dash
        String stringToBeReplaced = "-";
        StringBuilder builder
            = new StringBuilder();
 
        // Replace every matched pattern
        // with the target String
        // using replaceAll() method
        return (matcher
                    .replaceAll(stringToBeReplaced));
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given number in form of string
        String str = "1745389";
 
        // Function Call
        System.out.println(Insert_dash(str));
    }
}

Python

# Python program for the above approach
import re
 
# Function to insert dash - between
# any 2 consecutive odd digit
def Insert_dash(str):
 
    # Get the regex to be checked
    regex = "(?<=[13579])(?=[13579])"
 
    return re.sub(regex,'\1-\2', str)
 
# Driver Code
 
# Given number in form of string
str = "1745389"
 
# Function Call
print(Insert_dash(str))
 
# This code is contributed by yuvraj_chandra
Producción: 

1-745-389

 

Publicación traducida automáticamente

Artículo escrito por sj777 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 *