Leetcode 8. String to Integer (atoi)

Source: Internet
Author: User

https://leetcode.com/problems/string-to-integer-atoi/

Title: Converts a string to an integer.

Rules:

1. You can have more than one space before entering a string;

2. Encounters '-' or ' + ' or numeric characters starting with multiple numeric characters consecutively. That is encountered other characters end;

3. Multiple consecutive numeric characters may be followed by other characters, but not integers;

4. When the input is empty, or is a string that cannot be converted, output 0;

5. When the integer is greater than 2147483647, the output is 2147483647. When less than-2147483648, then output-2147483648

Idea: The main is to pay attention to overflow situation, in the process of traversal to determine whether overflow, or the final result can be more than 64 bits.

1 classSolution {2  Public:3     intMyatoi (stringstr) {4         intI=0, len=str.length ();5         if(len==0)6           return 0;7         intflag=0;8          while(i<len&&str[i]==' '){9i++;Ten         } One         if(str[i]=='-') A          { -flag=1; -i++; the          } -          Else if(str[i]=='+') -          { -i++; +          } -          Else if(str[i]<'0'|| Str[i]>'9') +          { A              return 0; at          } -         Long Longsum=0; -          while(i<Len) { -             if(str[i]>='0'&&str[i]<='9') -               { -sum=sum*Ten+ (str[i]-'0'); in                   if(sum>2147483647) -                       Break; to               } +             Else -                 Break; thei++; *         } $         intresult=sum;Panax Notoginseng         if(sum>2147483647){ -             if(flag) the              return-2147483648; +             Else A              return 2147483647; the         } +         Else -         { $             if(flag) $               return-result; -             Else -               returnresult; the         } -     }Wuyi};

Leetcode 8. 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.