leetcode.008 String to Integer (atoi)

Source: Internet
Author: User

Test Instructions

Converts a string containing a number to an int type

Ideas

Implementation is not difficult, mainly considering a variety of situations.

1. string is not an empty string;

2. what to do with spaces or other characters in a string;

3. with the sign processing;

4. What to do if the number in the string exceeds the range of type int (int range:-2147483648~2147483647 0x80000000~0x7fffffff)

1 intMyatoi (Char*str) {2     intlen=strlen (str);3     intflag=1, i=0;4     Long Longans=0;5     if(len==0)6         return 0;7     Else if(len==1)8     {9         if(str[0]>='0'&& str[0]<='9')Ten             returnstr[0]-'0'; One         Else return 0; A     } -     Else -     { the         intI=0; -          while(str[i]==' ') i++;//previous empty string skipped -         if(str[i]=='-') {flag=-1; i++;} -         Else  if(str[i]=='+') {flag=1; i++;} +         Else if(str[i]>='0'&& str[i]<='9') {flag=1;} -          while(str[i]!=' /') +         { A             if(str[i]>='0'&& str[i]<='9') at             { -ans=ans*Ten+str[i]-'0'; i++; -                 if(Flag*ans>int_max) {returnInt_max; Break;} -                 Else if(flag*ans<=int_min) {returnInt_min; Break;} -             } -             Else{returnAns*flag; Break;}//If a non-numeric string is encountered, the subsequent stop scan in      -         } to         return(int) (ANS) *Flag; +     } -}

leetcode.008 String to Integer (atoi)

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.