Reducir un número dado para formar una clave por las operaciones dadas

Dado un número entero N , la tarea es reducir el número y formar una clave siguiendo las operaciones que se indican a continuación:

  • Extraiga el dígito más significativo del número :
    • Si el dígito es par: Sume los dígitos consecutivos hasta que la suma de los dígitos sea impar.
    • Si el dígito es impar: suma los dígitos consecutivos hasta que la suma de los dígitos sea par.
  • Repita el proceso para todos los dígitos restantes.
  • Finalmente, concatene la suma calculada para obtener la clave.

Ejemplos:

Entrada: N = 1667848270
Salida: 20290
Explicación:
Paso 1: El primer dígito (= 1) es impar. Entonces, suma los siguientes dígitos hasta que la suma sea par.
Por lo tanto, los dígitos 1, 6, 6 y 7 se suman para formar 20.
Paso 2: El siguiente dígito (= 8) es par. Entonces, suma los siguientes dígitos hasta que la suma sea impar.
Por lo tanto, los dígitos 8, 4, 8, 2 y 7 se suman para formar 29.
Paso 3: El último dígito (= 0) es par.
Por tanto, la respuesta final tras concatenar los resultados será: 20290

Entrada: N = 7246262412
Salida: 342
Explicación:
Paso 1: El primer dígito (= 7) es impar. Entonces, suma los siguientes dígitos hasta que la suma sea par.
Por lo tanto, los dígitos 7, 2, 4, 6, 2, 6, 2, 4 y 1 se suman para formar 34.
Paso 2: El último dígito (= 2) es par.
Por tanto, la respuesta final tras concatenar los resultados será: 342.

 

Enfoque: La idea es iterar los dígitos del número y verificar la paridad del dígito . Si es par, continúe con los siguientes dígitos hasta que encuentre un dígito impar. Para dígitos impares, agregue dígitos consecutivos hasta que la suma de los dígitos sea par. Finalmente, concatene la suma calculada para obtener la clave deseada.

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

C++

// C++ program of the
// above approach
#include <bits/stdc++.h>
using namespace std;
 
 // Function to find the key
// of the given number
int key(int N)
{
     
    // Convert the integer
    // to String
    string num = "" + to_string(N);
    int ans = 0;
    int j = 0;
 
    // Iterate the num-string
    // to get the result
    for(j = 0; j < num.length(); j++)
    {
         
        // Check if digit is even or odd
        if ((num[j] - 48) % 2 == 0)
        {
            int add = 0;
            int i;
 
            // Iterate until odd sum
            // is obtained by adding
            // consecutive digits
            for(i = j; j < num.length(); j++)
            {
                add += num[j] - 48;
 
                // Check if sum becomes odd
                if (add % 2 == 1)
                    break;
            }
 
            if (add == 0)
            {
                ans *= 10;
            }
            else
            {
                int digit = (int)floor(log10(add) + 1);
                ans *= (pow(10, digit));
 
                // Add the result in ans
                ans += add;
            }
 
            // Assign the digit index
            // to num string
            i = j;
        }
        else
        {
             
            // If the number is odd
            int add = 0;
            int i;
 
            // Iterate until odd sum
            // is obtained by adding
            // consecutive digits
            for(i = j; j < num.length(); j++)
            {
                add += num[j] - 48;
 
                // Check if sum becomes even
                if (add % 2 == 0)
                {
                    break;
                }
            }
 
            if (add == 0)
            {
                ans *= 10;
            }
            else
            {
                int digit = (int)floor(
                       log10(add) + 1);
                ans *= (pow(10, digit));
 
                // Add the result in ans
                ans += add;
            }
 
            // assign the digit index
            // to main numstring
            i = j;
        }
    }
 
    // Check if all digits
    // are visited or not
    if (j + 1 >= num.length())
    {
        return ans;
    }
    else
    {
        return ans += num[num.length() - 1] - 48;
    }
}
 
// Driver code  
int main()
{
    int N = 1667848271;
     
    cout << key(N);
 
    return 0;
}
 
// This code is contributed by divyeshrabadiya07

Java

// Java program of the
// above approach
 
import java.io.*;
import java.util.*;
import java.lang.*;
 
public class Main {
    // Function to find the key
    // of the given number
    static int key(int N)
    {
 
        // Convert the integer
        // to String
        String num = "" + N;
        int ans = 0;
        int j = 0;
 
        // Iterate the num-string
        // to get the result
        for (j = 0; j < num.length(); j++) {
 
            // Check if digit is even or odd
            if ((num.charAt(j) - 48) % 2 == 0) {
                int add = 0;
                int i;
 
                // Iterate until odd sum
                // is obtained by adding
                // consecutive digits
                for (i = j; j < num.length(); j++) {
                    add += num.charAt(j) - 48;
 
                    // Check if sum becomes odd
                    if (add % 2 == 1)
                        break;
                }
 
                if (add == 0) {
                    ans *= 10;
                }
                else {
                    int digit = (int)Math.floor(
                        Math.log10(add) + 1);
                    ans *= (Math.pow(10, digit));
 
                    // Add the result in ans
                    ans += add;
                }
 
                // Assign the digit index
                // to num string
                i = j;
            }
            else {
                // If the number is odd
                int add = 0;
                int i;
 
                // Iterate until odd sum
                // is obtained by adding
                // consecutive digits
                for (i = j; j < num.length(); j++) {
                    add += num.charAt(j) - 48;
 
                    // Check if sum becomes even
                    if (add % 2 == 0) {
                        break;
                    }
                }
 
                if (add == 0) {
                    ans *= 10;
                }
                else {
                    int digit = (int)Math.floor(
                        Math.log10(add) + 1);
                    ans *= (Math.pow(10, digit));
 
                    // Add the result in ans
                    ans += add;
                }
 
                // assign the digit index
                // to main numstring
                i = j;
            }
        }
 
        // Check if all digits
        // are visited or not
        if (j + 1 >= num.length()) {
            return ans;
        }
        else {
            return ans += num.charAt(
                              num.length() - 1)
                          - 48;
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 1667848271;
        System.out.print(key(N));
    }
}

Python3

# Python3 program of the
# above approach
import math
 
# Function to find the key
# of the given number
def key(N) :
     
    # Convert the integer
    # to String
    num = "" + str(N)
    ans = 0
    j = 0
 
    # Iterate the num-string
    # to get the result
    while j < len(num) :
         
        # Check if digit is even or odd
        if ((ord(num[j]) - 48) % 2 == 0) :
     
            add = 0
 
            # Iterate until odd sum
            # is obtained by adding
            # consecutive digits
            i = j
            while j < len(num) :
                 
                add += ord(num[j]) - 48
 
                # Check if sum becomes odd
                if (add % 2 == 1) :
                    break
                 
                j += 1
 
            if (add == 0) :
             
                ans *= 10
         
            else :
             
                digit = int(math.floor(math.log10(add) + 1))
                ans *= (pow(10, digit))
 
                # Add the result in ans
                ans += add
 
            # Assign the digit index
            # to num string
            i = j
         
        else :
             
            # If the number is odd
            add = 0
 
            # Iterate until odd sum
            # is obtained by adding
            # consecutive digits
            i = j
            while j < len(num) :
             
                add += ord(num[j]) - 48
 
                # Check if sum becomes even
                if (add % 2 == 0) :
                 
                    break
                 
                j += 1
 
            if (add == 0) :
             
                ans *= 10
                 
            else :
             
                digit = int(math.floor(math.log10(add) + 1))
                ans *= (pow(10, digit))
 
                # Add the result in ans
                ans += add
 
            # assign the digit index
            # to main numstring
            i = j
         
        j += 1
 
    # Check if all digits
    # are visited or not
    if (j + 1) >= len(num) :
     
        return ans
 
    else :
        ans += ord(num[len(num) - 1]) - 48
        return ans
 
 
N = 1667848271
 
print(key(N))
 
# This code is contributed by divyesh072019

C#

// C# program of the
// above approach
using System;
class GFG{
    
// Function to find the key
// of the given number
static int key(int N)
{
  // Convert the integer
  // to String
  String num = "" + N;
  int ans = 0;
  int j = 0;
 
  // Iterate the num-string
  // to get the result
  for (j = 0; j < num.Length; j++)
  {
    // Check if digit is even or odd
    if ((num[j] - 48) % 2 == 0)
    {
      int add = 0;
      int i;
 
      // Iterate until odd sum
      // is obtained by adding
      // consecutive digits
      for (i = j; j < num.Length; j++)
      {
        add += num[j] - 48;
 
        // Check if sum becomes odd
        if (add % 2 == 1)
          break;
      }
 
      if (add == 0)
      {
        ans *= 10;
      }
      else
      {
        int digit = (int)Math.Floor(
                         Math.Log10(add) + 1);
        ans *= (int)(Math.Pow(10, digit));
 
        // Add the result in ans
        ans += add;
      }
 
      // Assign the digit index
      // to num string
      i = j;
    }
    else
    {
      // If the number is odd
      int add = 0;
      int i;
 
      // Iterate until odd sum
      // is obtained by adding
      // consecutive digits
      for (i = j; j < num.Length; j++)
      {
        add += num[j] - 48;
 
        // Check if sum becomes even
        if (add % 2 == 0)
        {
          break;
        }
      }
 
      if (add == 0)
      {
        ans *= 10;
      }
      else {
        int digit = (int)Math.Floor(
                         Math.Log10(add) + 1);
        ans *= (int)(Math.Pow(10, digit));
 
        // Add the result in ans
        ans += add;
      }
 
      // assign the digit index
      // to main numstring
      i = j;
    }
  }
 
  // Check if all digits
  // are visited or not
  if (j + 1 >= num.Length)
  {
    return ans;
  }
  else
  {
    return ans += num[num.Length - 1] - 48;
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  int N = 1667848271;
  Console.Write(key(N));
}
}
 
// This code is contributed by Rajput-Ji

Javascript

<script>
    // Javascript program of the above approach
     
    // Function to find the key
    // of the given number
    function key(N)
    {
     
      // Convert the integer
      // to String
      let num = "" + N.toString();
      let ans = 0;
      let j = 0;
 
      // Iterate the num-string
      // to get the result
      for (j = 0; j < num.length; j++)
      {
       
        // Check if digit is even or odd
        if ((num[j].charCodeAt() - 48) % 2 == 0)
        {
          let add = 0;
          let i;
 
          // Iterate until odd sum
          // is obtained by adding
          // consecutive digits
          for (i = j; j < num.length; j++)
          {
            add += num[j].charCodeAt() - 48;
 
            // Check if sum becomes odd
            if (add % 2 == 1)
              break;
          }
 
          if (add == 0)
          {
            ans *= 10;
          }
          else
          {
            let digit = Math.floor(Math.log10(add) + 1);
            ans *= parseInt(Math.pow(10, digit), 10);
 
            // Add the result in ans
            ans += add;
          }
 
          // Assign the digit index
          // to num string
          i = j;
        }
        else
        {
          // If the number is odd
          let add = 0;
          let i;
 
          // Iterate until odd sum
          // is obtained by adding
          // consecutive digits
          for (i = j; j < num.length; j++)
          {
            add += num[j].charCodeAt() - 48;
 
            // Check if sum becomes even
            if (add % 2 == 0)
            {
              break;
            }
          }
 
          if (add == 0)
          {
            ans *= 10;
          }
          else {
            let digit = Math.floor(Math.log10(add) + 1);
            ans *= parseInt(Math.pow(10, digit), 10);
 
            // Add the result in ans
            ans += add;
          }
 
          // assign the digit index
          // to main numstring
          i = j;
        }
      }
 
      // Check if all digits
      // are visited or not
      if (j + 1 >= num.length)
      {
        return ans;
      }
      else
      {
        return ans += num[num.length - 1].charCodeAt() - 48;
      }
    }
     
    let N = 1667848271;
      document.write(key(N));
     
    // This code is contributed by mukesh07.
</script>
Producción: 

20291

 

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

Publicación traducida automáticamente

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