Solution #1: Here is the code,
void reverse(char* str)
{
int len = strlen(str);
int start = 0;
int end = len - 1;
while(start < end)
{
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
char* itoa(int x)
{
char arr[50] = {0, 0};
int isNegative = 0;
int len = 0;
int index = 0;
if(x < 0)
{
isNegative = 1;
x *= -1;
}
while(x)
{
int i = x%10;
x = x/10;
arr[index++] = '0' + i;
}
if(isNegative)
arr[index++] = '-';
arr[index] = '\0';
reverse(arr);
char* ptr = (char*)malloc(index+1);
memcpy(ptr, arr, index+1);
return ptr;
}
int main()
{
printf("%s\n", itoa(-9247124));
return 0;
}
No comments:
Post a Comment