Implementa tu propio itoa()

La función itoa convierte un número entero en una string terminada en nulo. También puede convertir números negativos. La definición estándar de la función itoa se da a continuación: – 
 

C

char* itoa(int num, char* buffer, int base)

La base del tercer parámetro especifica la base de conversión. Por ejemplo: si la base es 2, convertirá el número entero en su string binaria compatible o si la base es 16, creará una forma de string hexadecimal convertida de número entero. 
Si la base es 10 y el valor es negativo, la string resultante va precedida de un signo menos (-). Con cualquier otra base, el valor siempre se considera sin firmar.
Referencia: http://www.cplusplus.com/reference/cstdlib/itoa/?kw=itoa
Ejemplos: 
 

  itoa(1567, str, 10) should return string "1567"
  itoa(-1567, str, 10) should return string "-1567"
  itoa(1567, str, 2) should return string "11000011111"
  itoa(1567, str, 16) should return string "61f"

Deben procesarse los dígitos individuales del número dado y sus caracteres correspondientes deben colocarse en la string dada. Usando divisiones repetidas por la base dada, obtenemos dígitos individuales desde el dígito menos significativo hasta el más significativo. Pero en la salida, estos dígitos se necesitan en orden inverso. Por lo tanto, invertimos la string obtenida después de la división repetida y la devolvemos.
 

C

/* A C++ program to implement itoa() */
#include <iostream>
using namespace std;
 
/* A utility function to reverse a string  */
void reverse(char str[], int length)
{
    int start = 0;
    int end = length -1;
    while (start < end)
    {
        swap(*(str+start), *(str+end));
        start++;
        end--;
    }
}
 
// Implementation of itoa()
char* itoa(int num, char* str, int base)
{
    int i = 0;
    bool isNegative = false;
 
    /* Handle 0 explicitly, otherwise empty string is printed for 0 */
    if (num == 0)
    {
        str[i++] = '0';
        str[i] = '\0';
        return str;
    }
 
    // In standard itoa(), negative numbers are handled only with
    // base 10. Otherwise numbers are considered unsigned.
    if (num < 0 && base == 10)
    {
        isNegative = true;
        num = -num;
    }
 
    // Process individual digits
    while (num != 0)
    {
        int rem = num % base;
        str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
        num = num/base;
    }
 
    // If number is negative, append '-'
    if (isNegative)
        str[i++] = '-';
 
    str[i] = '\0'; // Append string terminator
 
    // Reverse the string
    reverse(str, i);
 
    return str;
}
 
// Driver program to test implementation of itoa()
int main()
{
    char str[100];
    cout << "Base:10 " << itoa(1567, str, 10) << endl;
    cout << "Base:10 " << itoa(-1567, str, 10) << endl;
    cout << "Base:2 " << itoa(1567, str, 2) << endl;
    cout << "Base:8 " << itoa(1567, str, 8) << endl;
    cout << "Base:16 " << itoa(1567, str, 16) << endl;
    return 0;
}

Producción: 

Base:10 1567
Base:10 -1567
Base:2 11000011111
Base:8 3037
Base:16 61f

Complejidad de tiempo : O(n)

Espacio Auxiliar: O(1)

Este artículo es una contribución de Neha Mahajan . Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

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