Implement your own itoa()


itoa function converts an integer into a null-terminated string. It can convert negative numbers too. The standard definition of itoa function is given below:-


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

Examples:
  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"
/* A C++ program to implement itoa() */
#include 
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 isNegative = 0;
 int i = 0;
 
 if(num == 0){
     str[i++] = 0;
     str[i] = '\0';
     return str;
 }
 
 if(num < 0 && base ==10){
     isNegative = 1;
     num = -num;
 }
 
 while(num){
     int rem = num % base;
     str[i++] = rem >9 ? 'a' +(rem-10) : rem+'0';
     num = num/base;
 }
 
 if(isNegative == 1)
   str[i++] = '-';
 str[i] = '\0';
 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;
}



Comments