Search code examples
cstringinttype-conversionitoa

Convert integer to string without access to libraries


I recently read a sample job interview question:

Write a function to convert an integer to a string. Assume you do not have access to library functions i.e., itoa(), etc...

How would you go about this?


Solution

  • fast stab at it: (edited to handle negative numbers)

    int n = INT_MIN;
    char buffer[50];
    int i = 0;
    
    bool isNeg = n<0;
    
    unsigned int n1 = isNeg ? -n : n;
    
    while(n1!=0)
    {
        buffer[i++] = n1%10+'0';
        n1=n1/10;
    }
    
    if(isNeg)
        buffer[i++] = '-';
    
    buffer[i] = '\0';
    
    for(int t = 0; t < i/2; t++)
    {
        buffer[t] ^= buffer[i-t-1];
        buffer[i-t-1] ^= buffer[t];
        buffer[t] ^= buffer[i-t-1];
    }
    
    if(n == 0)
    {
        buffer[0] = '0';
        buffer[1] = '\0';
    }   
    
    printf(buffer);