Convertir un número de base A a base B

Dados dos enteros positivos A y B y una string S de tamaño N,  que denota un número en base A , la tarea es convertir la string S dada de base A a base B.

Ejemplos:

Entrada: S = “10B”, A = 16, B = 10
Salida: 267
Explicación: 10B en hexadecimal (base =16) cuando se convierte a decimal (base =10) es 267.

Entrada: S = “10011”, A = 2, B = 8
Salida: 23
Explicación: 10011 en binario (base = 2) cuando se convierte a octal (base = 8) es 23. 

Enfoque: Sistemas numéricos es la técnica para representar números en la arquitectura de sistemas informáticos . La arquitectura de la computadora admite los siguientes sistemas numéricos:

  • Sistema numérico binario (Base 2): El sistema numérico binario solo consta de dos dígitos, 0 s y 1 s. La base de este sistema numérico es 2 .
  • Sistema de numeración octal (base 8): El sistema de numeración octal consta de 8 dígitos que van del 0 al 7 .
  • Sistema numérico decimal (base 10): El sistema numérico decimal consta de 10 dígitos que van del 0 al 9 .
  • Sistema de numeración hexadecimal (Base 16): El sistema de numeración hexadecimal consta de 16 dígitos con 0 a 9 dígitos y alfabetos A a F. También se conoce como código alfanumérico, ya que consta de números y alfabetos.

Para convertir un número de base A a base B , la idea es convertirlo primero a su representación decimal y luego convertir el número decimal a base  B. 

Conversión de cualquier base a Decimal: El equivalente decimal del número “str” en base “base” es igual a 1 * str[len – 1] + base * str[len – 2] + (base) 2 * str[len – 3] + …

Conversión de decimal a cualquier base: 
el número decimal «inputNum» se puede convertir en un número en base «base» dividiendo repetidamente inputNum por la base y almacenando el resto. Finalmente, invierta la string obtenida para obtener el resultado deseado. 

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 return ASCII
// value of a character
int val(char c)
{
    if (c >= '0' && c <= '9')
        return (int)c - '0';
    else
        return (int)c - 'A' + 10;
}
 
// Function to convert a number
// from given base to decimal number
int toDeci(string str, int base)
{
    // Stores the length
    // of the string
    int len = str.size();
 
    // Initialize power of base
    int power = 1;
 
    // Initialize result
    int num = 0;
 
    // Decimal equivalent is str[len-1]*1
    // + str[len-2]*base + str[len-3]*(base^2) + ...
    for (int i = len - 1; i >= 0; i--) {
 
        // A digit in input number must
        // be less than number's base
        if (val(str[i]) >= base) {
            printf("Invalid Number");
            return -1;
        }
 
        // Update num
        num += val(str[i]) * power;
 
        // Update power
        power = power * base;
    }
 
    return num;
}
 
// Function to return equivalent
// character of a given value
char reVal(int num)
{
    if (num >= 0 && num <= 9)
        return (char)(num + '0');
    else
        return (char)(num - 10 + 'A');
}
 
// Function to convert a given
// decimal number to a given base
string fromDeci(int base, int inputNum)
{
    // Store the result
    string res = "";
 
    // Repeatedly divide inputNum
    // by base and take remainder
    while (inputNum > 0) {
 
        // Update res
        res += reVal(inputNum % base);
 
        // Update inputNum
        inputNum /= base;
    }
 
    // Reverse the result
    reverse(res.begin(), res.end());
 
    return res;
}
 
// Function to convert a given number
// from a base to another base
void convertBase(string s, int a, int b)
{
    // Convert the number from
    // base A to decimal
    int num = toDeci(s, a);
 
    // Convert the number from
    // decimal to base B
    string ans = fromDeci(b, num);
 
    // Print the result
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given input
    string s = "10B";
    int a = 16, b = 10;
 
    // Function Call
    convertBase(s, a, b);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to return ASCII
// value of a character
static int val(char c)
{
    if (c >= '0' && c <= '9')
        return(int)c - '0';
    else
        return(int)c - 'A' + 10;
}
 
// Function to convert a number
// from given base to decimal number
static int toDeci(String str, int base)
{
     
    // Stores the length
    // of the String
    int len = str.length();
 
    // Initialize power of base
    int power = 1;
 
    // Initialize result
    int num = 0;
 
    // Decimal equivalent is str[len-1]*1
    // + str[len-2]*base + str[len-3]*(base^2) + ...
    for(int i = len - 1; i >= 0; i--)
    {
         
        // A digit in input number must
        // be less than number's base
        if (val(str.charAt(i)) >= base)
        {
            System.out.printf("Invalid Number");
            return -1;
        }
 
        // Update num
        num += val(str.charAt(i)) * power;
 
        // Update power
        power = power * base;
    }
    return num;
}
 
// Function to return equivalent
// character of a given value
static char reVal(int num)
{
    if (num >= 0 && num <= 9)
        return(char)(num + '0');
    else
        return(char)(num - 10 + 'A');
}
 
// Function to convert a given
// decimal number to a given base
static String fromDeci(int base, int inputNum)
{
     
    // Store the result
    String res = "";
 
    // Repeatedly divide inputNum
    // by base and take remainder
    while (inputNum > 0)
    {
         
        // Update res
        res += reVal(inputNum % base);
 
        // Update inputNum
        inputNum /= base;
    }
 
    // Reverse the result
    res = reverse(res);
 
    return res;
}
 
// Function to convert a given number
// from a base to another base
static void convertBase(String s, int a, int b)
{
     
    // Convert the number from
    // base A to decimal
    int num = toDeci(s, a);
 
    // Convert the number from
    // decimal to base B
    String ans = fromDeci(b, num);
 
    // Print the result
    System.out.print(ans);
}
 
static String reverse(String input)
{
    char[] a = input.toCharArray();
    int l, r = a.length - 1;
    for(l = 0; l < r; l++, r--)
    {
        char temp = a[l];
        a[l] = a[r];
        a[r] = temp;
    }
    return String.valueOf(a);
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given input
    String s = "10B";
    int a = 16, b = 10;
 
    // Function Call
    convertBase(s, a, b);
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python program for the above approach
 
# Function to return ASCII
# value of a character
def val(c):
    if (c >= '0' and c <= '9'):
        return ord(c) - 48
    else:
        return ord(c) - 65  + 10
 
# Function to convert a number
# from given base to decimal number
def toDeci(strr, base):
     
    # Stores the length
    # of the string
    lenn = len(strr)
     
    # Initialize power of base
    power = 1
     
    # Initialize result
    num = 0
     
    # Decimal equivalent is strr[len-1]*1
    # + strr[len-2]*base + strr[len-3]*(base^2) + ...
    for i in range(lenn - 1, -1, -1):
        # A digit in input number must
        # be less than number's base
        if (val(strr[i]) >= base):
            print("Invalid Number")
            return -1
             
        # Update num
        num += val(strr[i]) * power
         
        # Update power
        power = power * base
     
    return num
 
# Function to return equivalent
# character of a given value
def reVal(num):
     
    if (num >= 0 and num <= 9):
        return chr(num + 48)
    else:
        return chr(num - 10 + 65)
 
 
# Function to convert a given
# decimal number to a given base
def fromDeci(base, inputNum):
     
    # Store the result
    res = ""
     
    # Repeatedly divide inputNum
    # by base and take remainder
    while (inputNum > 0):
         
        # Update res
        res += reVal(inputNum % base)
         
        # Update inputNum
        inputNum //= base
         
    # Reverse the result
    res = res[::-1]
     
    return res
 
 
# Function to convert a given number
# from a base to another base
def convertBase(s, a, b):
     
    # Convert the number from
    # base A to decimal
    num = toDeci(s, a)
 
    # Convert the number from
    # decimal to base B
    ans = fromDeci(b, num)
 
    # Print the result
    print(ans)
 
 
# Driver Code
 
# Given input
s = "10B"
a = 16
b = 10
 
# Function Call
convertBase(s, a, b)
 
# This code is contributed by shubhamsingh10

C#

// C# program for the above approach
using System;
 
public class GFG{
     
    // Function to return ASCII
    // value of a character
    static int val(char c)
    {
        if (c >= '0' && c <= '9')
            return(int)c - '0';
        else
            return(int)c - 'A' + 10;
    }
     
    // Function to convert a number
    // from given basse to decimal number
    static int toDeci(string str, int basse)
    {
         
        // Stores the length
        // of the string
        int len = str.Length;
     
        // Initialize power of basse
        int power = 1;
     
        // Initialize result
        int num = 0;
     
        // Decimal equivalent is str[len-1]*1
        // + str[len-2]*basse + str[len-3]*(basse^2) + ...
        for(int i = len - 1; i >= 0; i--)
        {
             
            // A digit in input number must
            // be less than number's basse
            if (val(str[i]) >= basse)
            {
                Console.Write("Invalid Number");
                return -1;
            }
     
            // Update num
            num += val(str[i]) * power;
     
            // Update power
            power = power * basse;
        }
        return num;
    }
     
    // Function to return equivalent
    // character of a given value
    static char reVal(int num)
    {
        if (num >= 0 && num <= 9)
            return(char)(num + '0');
        else
            return(char)(num - 10 + 'A');
    }
     
    // Function to convert a given
    // decimal number to a given basse
    static string fromDeci(int basse, int inputNum)
    {
         
        // Store the result
        string res = "";
     
        // Repeatedly divide inputNum
        // by basse and take remainder
        while (inputNum > 0)
        {
             
            // Update res
            res += reVal(inputNum % basse);
     
            // Update inputNum
            inputNum /= basse;
        }
     
        // Reverse the result
        res = reverse(res);
     
        return res;
    }
     
    // Function to convert a given number
    // from a basse to another basse
    static void convertbasse(string s, int a, int b)
    {
         
        // Convert the number from
        // basse A to decimal
        int num = toDeci(s, a);
     
        // Convert the number from
        // decimal to basse B
        string ans = fromDeci(b, num);
     
        // Print the result
        Console.Write(ans);
    }
     
    static string reverse(string input)
    {
        char[] a = input.ToCharArray();
        int l, r = a.Length - 1;
        for(l = 0; l < r; l++, r--)
        {
            char temp = a[l];
            a[l] = a[r];
            a[r] = temp;
        }
        return new string(a);
    }
     
    // Driver Code
    static public void Main (){
        // Given input
        string s = "10B";
        int a = 16, b = 10;
     
        // Function Call
        convertbasse(s, a, b);
    }
}
 
// This code is contributed by shubhamsingh10

Javascript

<script>
// Javascript program for the above approach
 
// Function to return ASCII
// value of a character
function val(c)
{
    if (c >= '0' && c <= '9')
        return c.charCodeAt(0) - 48;
    else
        return c.charCodeAt(0) - 65 + 10;
}
 
// Function to convert a number
// from given base to decimal number
function toDeci(str, base)
{
 
    // Stores the length
    // of the var
    var len = str.length;
 
    // Initialize power of base
    var power = 1;
 
    // Initialize result
    var num = 0;
 
    // Decimal equivalent is str[len-1]*1
    // + str[len-2]*base + str[len-3]*(base^2) + ...
    for (var i = len - 1; i >= 0; i--) {
 
        // A digit in input number must
        // be less than number's base
        if (val(str[i]) >= base) {
            document.write("Invalid Number");
            return -1;
        }
         
        // Update num
        num += val(str[i]) * power;
         
 
        // Update power
        power = power * base;
    }
 
    return num;
}
 
// Function to return equivalent
// character of a given valueString.fromCharCode
function reVal(num)
{
    if (num >= 0 && num <= 9)
        return String.fromCharCode(num + 48);
    else
        return String.fromCharCode(num - 10 + 65);
}
 
// Function to convert a given
// decimal number to a given base
function fromDeci(base, inputNum)
{
 
    // Store the result
    var res = "";
 
    // Repeatedly divide inputNum
    // by base and take remainder
    while (inputNum > 0) {
 
        // Update res
        res += reVal(inputNum % base);
 
        // Update inputNum
        inputNum = Math.floor(inputNum/base);
    }
 
    // Reverse the result
    res = res.split("").reverse().join("");
 
    return res;
}
 
// Function to convert a given number
// from a base to another base
function convertBase(s, a, b)
{
 
    // Convert the number from
    // base A to decimal
    var num = toDeci(s, a);
 
    // Convert the number from
    // decimal to base B
    var ans = fromDeci(b, num);
 
    // Print the result
    document.write(ans);
}
 
// Driver Code
// Given input
var s = "10B";
var a = 16
var b = 10;
 
// Function Call
convertBase(s, a, b);
 
// This code is contributed by ShubhamSingh10
</script>
Producción: 

267

 

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

Publicación traducida automáticamente

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