String to Integer (atoi)

Source: Internet
Author: User

Class Solution {public:    int atoi (string str) {        long long result=0;        int flag=1;        int i=0;        while (str[i]== ' &&str[i]!= ') {            i++;        }        if (str[i]== '-' &&str[i]!= ') {            flag=0;            i++;        } else if (str[i]== ' + ' &&str[i]!= ') {            i++;        }        for (; str[i]!= '; i++) {            if (str[i]>= ' 0 ' &&str[i]<= ' 9 ') {                                                if (flag) {                    result=result*10+ str[i]-' 0 ';                    if (RESULT>0X7FFFFFFF)                    return 0x7FFFFFFF;                } else{                    result=result*10-(str[i]-' 0 ');                    if (result< (signed int) 0x80000000)                    return 0x80000000;                }             } else break;        }        return (int) result;}                    ;

Attention:

1, the space before the character processing;

2. Invalid character input

3, Integer cross-border problem, here used a small trick, the return type is defined as long long. Then separate to determine whether the cross

32-bit integer range ((signed int) 0x80000000~0x7fffffff)

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.