LeetCode8 String to Integer (atoi)

Source: Internet
Author: User

Test instructions

Implement atoi to convert a string to an integer. (easy)

Analysis:

is to pay attention to a variety of special cases, boundary conditions of the judgment, see code comments.

1 classSolution {2  Public:3     intMyatoi (stringstr) {4         intStart =0;5         Long Longresult =0;6         intFlag =0;7         //handling of extra spaces at the beginning8          while(Str[start] = =' ') {                                     9start++;Ten         } One         if(Str[start] = ='+') { Astart++; -         } -         //"+-2" case, else if ... the         Else if(Str[start] = ='-') {                                    -start++; -Flag =1; -         } +         //illegal characters appear at the beginning -         if(Str[start] <'0'|| Str[start] >'9') {                      +             return 0; A         } at         //after the +-number processing, the extra 0 is started. -          while(Str[start] = ='0') {                                      -start++; -         } -          for(inti = start; I < str.size (); ++i) { -             //you can have extra numbers later . in             if(Str[i] <'0'|| Str[i] >'9') {                          -                 return(Flag = =0) ? Result:-result; to             } +             inttemp = Str[i]-'0'; -             //In this way, do not use POW (x, y) theresult = result *Ten+temp; *             //Handling of overflow $             if(Result >0x7FFFFFFF ) {                                 Panax Notoginseng                 return(Flag = =0) ?0x7FFFFFFF:0x80000000; -             } the         } +         if(Flag = =0) { A             returnresult;  the         } +         Else { -             return-result; $         } $  -     } -};

LeetCode8 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.