String to integer "123"-> 123

Source: Internet
Author: User
String to integer "123"-> 123

Description:
Enter a string composed of digits, convert it to an integer, and output it. For example, input string "123" and output integer 123.
Given function prototypeint StrToInt(const char *str)To convert a string to an integer. You cannot use the database function atoi.
Question Analysis:
To convert a string to an integer
① When scanning the first character '1', the number 1 is obtained directly because it is the first character.
② When scanning the second character '2,1*10+2 = 12
③ When the scan character '3' continues,12*10+3=123
That's whyn = n * 10 + c;
Easy to error:
1) it cannot be a null pointer. Otherwise, the program will crash when the NULL pointer is accessed.if(str == NULL)return 0;
2) Positive and Negative symbols must be considered.Add sign
3) consider invalid characters, such as spaces.While (isspace (* Str) ++ STR also needs to be detected when it is a number before conversion starts.
4) integer overflow. If a long and long string is input, it may be converted into integer overflow.Method 1: The N type can be defined as long. Method 2: Use the max_int and min_int types to compare the sizes of N and max_int/10.
<<
Reference code:

Int strtoint (const char * Str) {// reverse the value of 0 and move one static const int max_int = (INT) (unsigned )~ 0> 1); static const int min_int =-(INT) (unsigned )~ 0> 1)-1; unsigned int n = 0; // determines whether it is null if (STR = NULL) return 0; // process space while (isspace (* Str) + + STR; // process positive and negative int Sign = 1; if (* STR = '+' | * STR = '-') {If (* STR = '-') Sign =-1; ++ STR ;} // after confirming the number, start converting while (isdigit (* Str) {// handle overflow int c = * str-'0 '; if (sign> 0 & (n> max_int/10 | (n = max_int/10 & C> max_int % 10) {n = max_int; break ;} else if (sign <0 & (n> (unsigned) min_int/10 | (n = (Unsigned) min_int/10 & C> (unsigned) min_int % 10) {n = min_int; break;} n = N * 10 + C; ++ STR;} return sign> 0? N:-N ;}


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.