Converts the number of integer n to the corresponding string, saved in S (two methods)

Source: Internet
Author: User

Method One,

Use the Loop method to remove each bit, save in the character array, and then flip the array.

The code is implemented as follows:

#include <stdio.h>
#include <string.h>
#include <assert.h>
#define MAX 20
void reverse (char *left, char *right)
{
ASSERT (left);
ASSERT (right);
while (left < right)
{
int tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
char *itoa (int value, char *s)
{
char *ps = s;
int size = 0;
while (value)
{
*ps=value% + + ' 0 ';
Value/= 10;
ps++;
}
*ps = ' + ';
Size=strlen (s);
Reverse (S, s+size-1);
return s;
}

int main ()
{
int value = 0;
Char Arr[max] = {0};
scanf ("%d", &value);
Itoa (Value,arr);
printf ("%s", arr);
System ("pause");
return 0;
}

Method Two,

Each bit is output in a recursive way. Because when you call yourself (recursively), you save the variable in the run-time stack, and finally when you output the variable at the end of the recursion, the value from the run-time stack does not need to be flipped.

The code is implemented as follows:

#include <stdio.h>

void itoa (int value)
{
if (value >= 10)
{
Itoa (VALUE/10);

}
printf ("%d", value% 10);
}

int main ()
{
int value = 0;
scanf ("%d", &value);
Itoa (value);
System ("pause");
return 0;
}

Converts the number of integer n to the corresponding string, saved in S (two methods)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.