| write code to implement itoa()... | |||||||
|
30 Day Risk-Free Guarantee:
100% money back if you're unsatisfied. Book (308 Pages):
![]() Video (One Hour):
![]() Resume Review (24 - 48hr)
All Products / Services
|
|||||||
char* itoa(int n) {
char* ret = NULL;
int numChars = 0;
// Determine if integer is negative
bool isNegative = false;
if (n < 0) {
n = -n;
isNegative = true;
numChars++;
}
// Count how much space we will need for the string
int temp = n;
do {
numChars++;
temp /= 10;
} while ( temp );
//Allocate space for the string (1 for negative sign, 1 for each digit, and 1 for null terminator)
ret = new char[ numChars + 1 ];
ret[numChars] = 0;
//Add the negative sign if needed
if (isNegative) ret[0] = '-';
// Copy digits to string in reverse order
int i = numChars - 1;
do {
ret[i--] = n%10 + '0';
n /= 10;
} while (n);
return ret;
}
char* itoa(int x) {
int i = x < 0 ? 3 : 2;
int t = abs(x);
while (t = t / 10) ++i;
char* s = new char[i];
s[--i] = '\0';
t = abs(x);
while (i) s[--i] = '0' + (t % 10), t = t / 10;
if (x < 0) s[0] = '-';
return s;
}
#include<stdio.h>
#include<stdlib.h>void reverse(char *str,int len) {
int i=0;
char ch;
for(i=0;i<=(len-1)/2;i++) {
ch=str[i];
str[i]=str[len-1-i];
str[len-1-i]=ch;
}
}char* itoa(int number) {
char *str=malloc(sizeof(char)*20);
int negFlag=0,pos=0;
if(number<0) {
negFlag=1;
number=-number;
}
while(number>0) {
str[pos++]='0'+number%10;
number=number/10;
}
if(negFlag) {
str[pos++]='-';
}
str[pos]='\0';
reverse(str,pos);
return str;
}int main() {
printf("reverse %d : %s ",-543,itoa(-543));
printf("reverse %d : %s ",54,itoa(54));
printf("reverse %d : %s ",5,itoa(5));
}
you guys should also consider base, how about binary? decimal? hex?
int myitoa(char *num)
{
int i =0;
while( *num )
{
i = i<<3 + i<<1 + (*s - '0') ;
s++;
}
return i;
}
int myitoa(char *num)
{
int i =0;
while( *num )
{
i = i<<3 + i<<1 + (*s - '0') ;
s++;
}
return i;
}
convert to string, then reverse the string.