Convertir un número de base 2 a base 6

Dado un entero binario N , la tarea es convertirlo en base 6.

Nota: El número de bits en N es hasta 100. 

Ejemplos:

Entrada: N = “100111”
Salida: 103
Explicación: El entero dado (100111) 2 es equivalente a (103) 6 .

Entrada: N = “1111111”
Salida: 331

 

Enfoque: El problema dado se puede resolver convirtiendo primero el número entero dado a decimal , luego convirtiendo el número de decimal a la base 6 usando un enfoque discutido aquí . Tenga en cuenta que dado que el valor de N puede alcanzar hasta 2 100 , el entero de 128 bits se puede usar para almacenar el número decimal. 

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;
 
// Program to convert the base of
// given binary number to base 6
void convertBase(string N)
{
    // 128 bit integer to store
    // the decimal conversion
    __int128 decimal = 0;
 
    // Loop to iterate N
    for (int i = 0; i < N.length(); i++) {
        // Binary to decimal
        decimal = decimal * 2 + (N[i] - '0');
    }
 
    // Stores the base 6 int
    vector<int> ans;
 
    // Decimal to base 6
    while (decimal > 0) {
        ans.push_back(decimal % 6);
        decimal = decimal / 6;
    }
 
    // Print Answer
    for (int i = ans.size() - 1; i >= 0; i--) {
        cout << ans[i];
    }
}
 
// Driver Code
int main()
{
    string N = "100111";
    convertBase(N);
 
    return 0;
}

C

// C program to implement the above approach
#include <stdio.h>
#include <stdint.h>
#include <string.h>
 
// Program to convert the base of
// given binary number to base 6
void convertBase(char* N)
{
    // 128 bit integer to store
    // the decimal conversion
    __int128 decimal = 0;
     
      //calculating length of N
      int len = strlen(N);
    // Loop to iterate N
    for (int i = 0; i < len; i++) {
        // Binary to decimal
        decimal = decimal * 2 + (N[i] - '0');
    }
 
    // Stores the base 6 int
    int ans[len];
       
      //to calculate index in ans
      int pos = 0;
 
    // Decimal to base 6
    while (decimal > 0) {
        ans[pos++] = (decimal % 6);
        decimal = decimal / 6;
    }
 
    // Print Answer
    for (int i = pos - 1; i >= 0; i--) {
        printf("%d", ans[i]);
    }
}
 
// Driver Code
int main()
{
    char* N = "100111";
    convertBase(N);
 
    return 0;
}
 
// This code is contributed by phalasi.

Java

// JAVA program of the above approach
import java.util.*;
class GFG {
 
    // Program to convert the base of
    // given binary number to base 6
    public static void convertBase(String N)
    {
 
        // 128 bit integer to store
        // the decimal conversion
        int decimal = 0;
 
        // Loop to iterate N
        for (int i = 0; i < N.length(); i++) {
            // Binary to decimal
            decimal = decimal * 2 + (N.charAt(i) - '0');
        }
 
        // Stores the base 6 int
        ArrayList<Integer> ans = new ArrayList<Integer>();
 
        // Decimal to base 6
        while (decimal > 0) {
            ans.add(decimal % 6);
            decimal = decimal / 6;
        }
 
        // Print Answer
        for (int i = ans.size() - 1; i >= 0; i--) {
            System.out.print(ans.get(i));
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String N = "100111";
        convertBase(N);
    }
}
 
// This code is contributed by Taranpreet

Python3

# Python code for the above approach
 
# Program to convert the base of
# given binary number to base 6
 
 
def convertBase(N):
 
    # 128 bit integer to store
    # the decimal conversion
    decimal = 0
 
    # Loop to iterate N
    for i in range(len(N)):
 
        # Binary to decimal
        decimal = decimal * 2 + (ord(N[i]) - ord('0'))
 
    # Stores the base 6 int
    ans = []
 
    # Decimal to base 6
    while (decimal > 0):
        ans.append(decimal % 6)
        decimal = decimal // 6
 
    # Print Answer
    for i in range(len(ans) - 1, -1, -1):
        print(ans[i], end="")
 
 
# Driver Code
N = "100111"
convertBase(N)
 
# This code is contributed by gfgking

C#

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Program to convert the base of
    // given binary number to base 6
    public static void convertBase(string N)
    {
 
        // 128 bit integer to store
        // the decimal conversion
        int decimall = 0;
 
        // Loop to iterate N
        for (int i = 0; i < N.Length; i++) {
            // Binary to decimal
            decimall = decimall * 2 + (N[i] - '0');
        }
 
        // Stores the base 6 int
        List<int> ans = new List<int>();
 
        // Decimal to base 6
        while (decimall > 0) {
            ans.Add(decimall % 6);
            decimall = decimall / 6;
        }
 
        // Print Answer
        for (int i = ans.Count - 1; i >= 0; i--) {
            Console.Write(ans[i]);
        }
    }
 
    // Driver Code
    public static void Main()
    {
        string N = "100111";
        convertBase(N);
    }
}
 
// This code is contributed by sanjoy_62.

Javascript

<script>
        // JavaScript code for the above approach
 
        // Program to convert the base of
        // given binary number to base 6
        function convertBase(N)
        {
         
            // 128 bit integer to store
            // the decimal conversion
            let decimal = 0;
 
            // Loop to iterate N
            for (let i = 0; i < N.length; i++)
            {
             
                // Binary to decimal
                decimal = decimal * 2 +
                (N[i].charCodeAt(0) -
                '0'.charCodeAt(0));
            }
 
            // Stores the base 6 int
            let ans = [];
 
            // Decimal to base 6
            while (decimal > 0) {
                ans.push(decimal % 6);
                decimal = Math.floor(decimal / 6);
            }
 
            // Print Answer
            for (let i = ans.length - 1; i >= 0; i--) {
                document.write(ans[i]);
            }
        }
 
        // Driver Code
        let N = "100111";
        convertBase(N);
 
       // This code is contributed by Potta Lokesh
    </script>
Producción

103

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

Otro enfoque: el problema dado también se puede resolver manteniendo el número entero en base 6 en lugar de la conversión decimal mientras se convierte la base del número entero binario a decimal . Se sabe que el número binario se puede convertir a decimal siguiendo los siguientes pasos:

N = “1001”
N se puede convertir a (N) 10 con la ecuación: (((1*2 + 0) *2 + 0) *2) + 1).

Por lo tanto, se requieren dos tipos de pasos, multiplicar el número entero por 2 que es equivalente a sumar el número entero en sí mismo, y sumar 0 o 1 al número entero como (0, 1) 2 es equivalente a (0, 1 ) 6 . Por lo tanto, mantenga una string que represente un entero de base 6 y, en cada paso, agregue el entero a sí mismo y agregue 0 o 1 según corresponda en cada paso. Si se puede hacer usando el enfoque discutido aquí .

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 sum of
// two integers of base B
string sumBaseB(string a, string b, int base)
{
    int len_a, len_b;
 
    len_a = a.size();
    len_b = b.size();
 
    string sum, s;
    s = "";
    sum = "";
 
    int diff;
    diff = abs(len_a - len_b);
 
    // Padding 0 in front of the
    // number to make both numbers equal
    for (int i = 1; i <= diff; i++)
        s += "0";
 
    // Condition to check if the strings
    // have lengths mis-match
    if (len_a < len_b)
        a = s + a;
    else
        b = s + b;
 
    int curr, carry = 0;
 
    // Loop to find the find the sum
    // of two integers of base B
    for (int i = max(len_a, len_b) - 1; i > -1; i--) {
        // Current Place value for
        // the resultant sum
        curr = carry + (a[i] - '0') + (b[i] - '0');
 
        // Update carry
        carry = curr / base;
 
        // Find current digit
        curr = curr % base;
 
        // Update sum result
        sum = (char)(curr + '0') + sum;
    }
    if (carry > 0)
        sum = (char)(carry + '0') + sum;
    return sum;
}
 
// Program to convert the base of
// given binary number to base 6
string convertBase(string N)
{
    // Stores the required answer
    string ans = "0";
 
    // Loop to iterate N
    for (int i = 0; i < N.length(); i++) {
        // Multiply the current
        // integer with 2
        ans = sumBaseB(ans, ans, 6);
 
        // Add N[i] to ans
        ans = sumBaseB(ans, (N[i] == '0')
                                ? "0"
                                : "1",
                       6);
    }
 
    // Return Answer
    return ans;
}
 
// Driver Code
int main()
{
    string N = "100111";
    cout << convertBase(N);
 
    return 0;
}

Java

// Java program of the above approach
 
class GFG{
 
// Function to find the sum of
// two integers of base B
static String sumBaseB(String a, String b, int base)
{
    int len_a, len_b;
 
    len_a = a.length();
    len_b = b.length();
 
    String sum, s;
    s = "";
    sum = "";
 
    int diff;
    diff = Math.abs(len_a - len_b);
 
    // Padding 0 in front of the
    // number to make both numbers equal
    for (int i = 1; i <= diff; i++)
        s += "0";
 
    // Condition to check if the Strings
    // have lengths mis-match
    if (len_a < len_b)
        a = s + a;
    else
        b = s + b;
 
    int curr, carry = 0;
 
    // Loop to find the find the sum
    // of two integers of base B
    for (int i = Math.max(len_a, len_b) - 1; i > -1; i--) {
        // Current Place value for
        // the resultant sum
        curr = carry + (a.charAt(i) - '0') + (b.charAt(i) - '0');
 
        // Update carry
        carry = curr / base;
 
        // Find current digit
        curr = curr % base;
 
        // Update sum result
        sum = (char)(curr + '0') + sum;
    }
    if (carry > 0)
        sum = (char)(carry + '0') + sum;
    return sum;
}
 
// Program to convert the base of
// given binary number to base 6
static String convertBase(String N)
{
    // Stores the required answer
    String ans = "0";
 
    // Loop to iterate N
    for (int i = 0; i < N.length(); i++) {
        // Multiply the current
        // integer with 2
        ans = sumBaseB(ans, ans, 6);
 
        // Add N[i] to ans
        ans = sumBaseB(ans, (N.charAt(i) == '0')
                                ? "0"
                                : "1",
                       6);
    }
 
    // Return Answer
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    String N = "100111";
    System.out.print(convertBase(N));
 
}
}
 
// This code contributed by shikhasingrajput

Python3

# Python program of the above approach
 
# Function to find the sum of
# two integers of base B
def sumBaseB(a, b, base):
  len_a = len(a);
  len_b = len(b);
 
  s = ""
  sums = ""
 
  diff = abs(len_a - len_b)
 
  # Padding 0 in front of the
  # number to make both numbers equal
  for i in range(1, diff + 1):
    s += "0"
     
  # Condition to check if the strings
  # have lengths mis-match
  if (len_a < len_b):
    a = s + a
  else:
    b = s + b
 
  curr, carry = 0, 0
 
  # Loop to find the find the sum
  # of two integers of base B
  i = max(len_a, len_b) - 1
  while (i > -1):
    curr = carry + int(a[i]) + int(b[i])
    carry = int(curr / base)
    curr = curr % base
    sums = str(curr) + sums
    i -= 1
     
  if carry > 0:
    sums = str(carry) + sums
     
  return sums
 
# function to convert base of binary num to base 6
def convertBase(N):
  ans = ""
  for i in range(0, len(N)):
    ans = sumBaseB(ans, ans, 6)
    ans = sumBaseB(ans, ["1", "0"][N[i] == "0"], 6)
  return ans
 
N = "100111"
print(convertBase(N))
 
# This code is contributed by phalasi.

C#

// C# program of the above approach
using System;
class GFG{
 
  // Function to find the sum of
  // two integers of base B
  static string sumBaseB(string a, string b, int base1)
  {
    int len_a, len_b;
 
    len_a = a.Length;
    len_b = b.Length;
 
    string sum, s;
    s = "";
    sum = "";
 
    int diff;
    diff = Math.Abs(len_a - len_b);
 
    // Padding 0 in front of the
    // number to make both numbers equal
    for (int i = 1; i <= diff; i++)
      s += "0";
 
    // Condition to check if the Strings
    // have lengths mis-match
    if (len_a < len_b)
      a = s + a;
    else
      b = s + b;
 
    int curr, carry = 0;
 
    // Loop to find the find the sum
    // of two integers of base B
    for (int i = Math.Max(len_a, len_b) - 1; i > -1; i--) {
      // Current Place value for
      // the resultant sum
      curr = carry + (a[i] - '0') + (b[i] - '0');
 
      // Update carry
      carry = curr / base1;
 
      // Find current digit
      curr = curr % base1;
 
      // Update sum result
      sum = (char)(curr + '0') + sum;
    }
    if (carry > 0)
      sum = (char)(carry + '0') + sum;
    return sum;
  }
 
  // Program to convert the base of
  // given binary number to base 6
  static string convertBase(string N)
  {
    // Stores the required answer
    string ans = "0";
 
    // Loop to iterate N
    for (int i = 0; i < N.Length; i++) {
      // Multiply the current
      // integer with 2
      ans = sumBaseB(ans, ans, 6);
 
      // Add N[i] to ans
      ans = sumBaseB(ans, (N[i] == '0')
                     ? "0"
                     : "1",
                     6);
    }
 
    // Return Answer
    return ans;
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    string N = "100111";
    Console.WriteLine(convertBase(N));
 
  }
}
 
// This code is contributed by ukasp.

Javascript

// JS program of the above approach
 
// Function to find the sum of
// 2 integers of base B
function sumBaseB(a, b, base)
{
    var len_a = a.length;
    var len_b = b.length;
     
    var s = "";
    var sums = "";
     
    var diff = Math.abs(len_a - len_b);
     
    // Padding 0 in front of the number to
    // make the both numbers equal
    for (var i = 1; i <= diff; i++)
    {
        s += "0";
    }
     
    // condition to check if the strings
    // have mismatch in lengths
    if (len_a < len_b)
    {
        a = s + a;
    }
    else
    {
        b = s + b;
    }
     
    var curr = 0;
    var carry = 0;
     
    // loop to find the sum of 2
    // integers of base B
     
    var i = Math.max(len_a, len_b) - 1
    while (i > -1)
    {
        curr = carry + parseInt(a[i]) + parseInt(b[i]);
        carry = parseInt(curr / base);
        curr %= base;
        sums = String(curr) + sums;
        i--;
    }
     
    if (carry > 0)
        sums = String(carry) + sums;
         
    return sums;
}
 
// function to convert base 2 number to base 6
function convertBase(N)
{
    let ans = "";
    for (var i = 0; i < N.length; i++)
    {
        ans = sumBaseB(ans, ans, 6);
        ans = sumBaseB(ans, (N[i] == "0") ? "0" : "1", 6);
    }
    return ans;
}
 
// Driver code
let N = "100111";
document.write(convertBase(N));
 
//This code is contributed by phasing17.
Producción

103

Complejidad de Tiempo: O(len(N) 2 )
Espacio Auxiliar: O(len(N))

Tenga en cuenta que la complejidad del primer enfoque es menor que la del segundo enfoque, pero el primer enfoque solo puede manejar números enteros binarios de hasta 127 bits, mientras que el segundo enfoque también puede manejar valores mucho más grandes.

Publicación traducida automáticamente

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