La potencia menor más cercana de 2 para cada dígito de un número

Dado un número entero , la tarea para cada dígito del número es encontrar la potencia de 2 más alta que no exceda ese dígito.

Ejemplos:

Entrada: num = 4317
Salida: 4214
Explicación: 
La mayor potencia de 2 ≤ 4 es 4.
La mayor potencia de 2 ≤ 3 es 2.
La mayor potencia de 2 ≤ 1 es 1.
La mayor potencia de 2 ≤ 7 es 4.

Entrada: núm = 8015
Salida: 8014

Enfoque: siga los pasos a continuación para resolver el problema:

  1. Convierte el número a su string equivalente .
  2. Atraviesa la cuerda .
  3. Si el dígito es ‘0’ , imprima 0 .
  4. De lo contrario, para cada dígito x , calcule 2 (log 2 (x)) .

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

C++

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the nearest power of
// two for every digit of a given number
void highestPowerOfTwo(int num)
{
    // Converting number to string
    string s = to_string(num);
 
    // Traverse the array
    for (int i = 0; i < (int)s.size();
         i++) {
 
        if (s[i] == '0') {
            cout << "0";
            continue;
        }
 
        // Calculate log base 2
        // of the current digit s[i]
        int lg = log2(int(s[i]) - 48);
 
        // Highest power of 2 <= s[i]
        int p = pow(2, lg);
 
        // ASCII conversion
        cout << char(p + 48);
    }
}
 
// Driver Code
int main()
{
    int num = 4317;
    highestPowerOfTwo(num);
 
    return 0;
}

Java

// Java program to implement
// the above approach
import java.util.*;
class GFG
{
 
  // Function to find the nearest power of
  // two for every digit of a given number
  static void highestPowerOfTwo(int num)
  {
 
    // Converting number to string
    String s = Integer.toString(num);
 
    // Traverse the array
    for (int i = 0; i < (int)s.length(); i++)
    {
 
      if (s.charAt(i) == '0')
      {
        System.out.print("0");
        continue;
      }
 
      // Calculate log base 2
      // of the current digit s[i]
      int lg
        = (int)(Math.log(s.charAt(i) - '0') / Math.log(2));
 
      // Highest power of 2 <= s[i]
      int p = (int)Math.pow(2, lg);
 
      // ASCII conversion
      System.out.print((char)(p + 48));
    }
  }
 
  // Driver Code
  public static void main(String args[])
  {
    int num = 4317;
    highestPowerOfTwo(num);
  }
}
 
// This code is contributed by susmitakundugoaldanga.

Python3

# Python 3 program for the above approach
import math
 
# Function to find the nearest power of
# two for every digit of a given number
def highestPowerOfTwo(num) :
     
    # Converting number to string
    s = str(num)
 
    # Traverse the array
    for i in range(len(s)):
        if (s[i] == '0') :
            print("0")
            continue
         
        # Calculate log base 2
        # of the current digit s[i]
        lg = int(math.log2(ord(s[i]) - 48))
 
        # Highest power of 2 <= s[i]
        p = pow(2, lg)
 
        # ASCII conversion
        print(chr(p + 48), end = "")
     
# Driver Code
num = 4317
highestPowerOfTwo(num)
 
# This code is contributed by code_hunt.

C#

// C# program to implement
// the above approach
using System;
class GFG
{
 
    // Function to find the nearest power of
    // two for every digit of a given number
    static void highestPowerOfTwo(int num)
    {
        // Converting number to string
        String s = num.ToString();
 
        // Traverse the array
        for (int i = 0; i < (int)s.Length; i++)
        {
 
            if (s[i] == '0')
            {
                Console.Write("0");
                continue;
            }
 
            // Calculate log base 2
            // of the current digit s[i]
            int lg
                = (int)(Math.Log(s[i] - '0') / Math.Log(2));
 
            // Highest power of 2 <= s[i]
            int p = (int)Math.Pow(2, lg);
 
            // ASCII conversion
            Console.Write((char)(p + 48));
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int num = 4317;
        highestPowerOfTwo(num);
    }
}
 
// This code is contributed by subhammahato348.

Javascript

<script>
      // JavaScript program to implement
      // the above approach
 
      // Function to find the nearest power of
      // two for every digit of a given number
      function highestPowerOfTwo(num) {
        // Converting number to string
        var s = num.toString();
 
        // Traverse the array
        for (var i = 0; i < s.length; i++) {
          if (s[i] === "0") {
            document.write("0");
            continue;
          }
 
          // Calculate log base 2
          // of the current digit s[i]
          var lg = parseInt(Math.log2(s[i].charCodeAt(0) - 48));
 
          // Highest power of 2 <= s[i]
          var p = Math.pow(2, lg);
 
          // ASCII conversion
          document.write(String.fromCharCode(p + 48));
        }
      }
 
      // Driver Code
      var num = 4317;
      highestPowerOfTwo(num);
    </script>
Producción: 

4214

 

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

Publicación traducida automáticamente

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