Implementation of atoi and ITOA

Source: Internet
Author: User

Let's start with ITOA and convert numbers into strings. TheAdd '0' after the number to convert it to char typeIn this way, after each number is converted to Char, it becomes an array of characters in reverse order, and then in reverse order.

Atoi is an integer that is equal to Char-'0.

Notes in the Code:

1. Function Name: you can imagine that atoi has a return value to identify whether conversion is successful.

// The parameter must be constbool atoi (const char * pstr, Int & nvalue)

2. In atoi, you can determine whether a character cannot be converted to a number in the following way:

If (pstr [I]> = '0' & pstr [I] <= '9') {// conversion} else {return false ;}

3. Determine the overflow in atoi:

if(nValue > std::numeric_limits<int>::max()){      return false;}

4. Consider setting the converted numeric type to a greater value, such as long.

 

Self-implemented:

Void itoamyself (INT number, char STR []) {bool bnagetive = false; If (number <0) {bnagetive = true; number = 0-number;} int I = 0; char TMP [12]; // convert the number to Char while (number) {TMP [I] = Number % 10 + '0'; I ++; number = Number/10;} If (bnagetive) {TMP [I ++] = '-';} TMP [I] = '\ 0'; I --; // cout <"tmp []:" <TMP <Endl; Int J = 0; // convert the reverse Char to a forward string while (I> = 0); {STR [J ++] = TMP [I --];} STR [J] = '\ 0 ';}
Bool atoimyself (char * STR, Int & number) {int I = 0, j = 0; bool bnagetive = false; If (! Str) return false; char TMP [12]; // space or tab while (STR [I] = ''| STR [I] = '/t ') {I ++;} If (STR [I] = '-') {bnagetive = true; I ++;} // cout <"str []: "<STR <Endl; int sum = 0; while (STR [I]) {// If (isnumber (STR [I]-'0') return false; sum = STR [I]-'0' + sum * 10; I ++;} If (bnagetive) sum =-sum; number = sum; return true ;}

Appendix: convert a string to an integer to implement [He Haitao]

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.