Narrative description of the problem:
Implement atoi to convert a string to an integer.
Problem-Solving ideas:
For a string, the following points need to be noted:
1. All air filters at the beginning of the string character;
2. Note the "+" and "-" characters in front of the numeric characters. So as to determine the positive and negative numbers;
3, processing only numeric characters, once non-numeric characters appear. Immediately stops the string processing and returns the processed results;
4. When returning the result, we should pay attention to the problem of digital crossing. cannot be greater than the maximum value and cannot be less than the minimum value.
Class Solution {Public:int atoi (const char *str) {if (str = = NULL) return 0; const char *pcur = str; Long long result = 0; int flag = 0;/* Indicates whether the number is negative */while (*pcur = = ' && *pcur! = ') ') pcur++; if (*pcur = = ') */* There is only a space in the string */return 0; if (*pcur = = ' + ')/* handles the symbol in front of the string */pcur++; else if (*pcur = = '-') {flag = 1; pcur++; } if (*pcur > ' 9 ' | | *pcur < ' 0 ')/* plus minus sign followed by illegal character, jump out of processing */return 0; if (*pcur! = ') "result = _atoi_core (pcur, flag); return (int) result; } Long Long _atoi_core (const char * pcur, int flag) {Long long result; while (*pcur! = ')} {if (*pcur >= ' 0 ' && *pcur <= ' 9 ') {result = result*10 + * pCur-48; pcur++; } else/* encounters illegal characters and jumps out of processing */break; } if (Result > 0x7FFFFFFF) {if (flag) return int_min; else return Int_max; } if (flag) result = 0-result; return result; }};
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
Convert a string into a number