Implementation of atoi and itoa Functions

Source: Internet
Author: User

1. Implementation of itoa

// 1234 → 4321 storage: str = n % radix, n = n/radix) → 1234
// Todo: Just write down the content containing negative numbers.

Char * my_itoa2 (int num, char * string, int radix)
{
Char * str = string;

// Obtain the flipped string
While (num)
{
* Str = num % radix + '0'; // * str = num % radix-'0'; it is wrong, haha.
// Cout <* str <endl;
Num = num/radix;
Str ++;
}
* Str = '\ 0 ';

Char temp;
Int len = strlen (str );
For (int I = 0; I <len/2; I ++)
{
Temp = str [I];
Str [I] = str [len-1-i];
Str [len-1-i] = temp;
}
Return string;
}


2 atoi implementation

// Num = num * 10 + * str;
// Todo: consider the situation where the border is crossed.

Int my_atoi (char * str)
{
If (str = NULL) return 0;
Int num = 0, flag = 1;

If (* str = '-')
{
Flag =-1;
}
Else
{
Num = * str-'0 ';
}
Str ++;

// While (* st> = '0' & * str <= '9 ')
While (* str! = '\ 0 ')
{
Num = num * 10 + * str-'0 ';
Str ++;
}

Return num * flag;
}



3 test code

Int main ()
{

Char * s = "-123567890 ";
Cout <my_atoi (s) <endl;

Int a = 1234;
// * Char str [20] = {'\ 0'}; // pre-defined
Char * str = new char [20];
Str = my_itoa2 (a, str, 10 );
Cout <str <endl;

Return 0;
}


Related Article

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.