leetcode No8. String to Integer (atoi)_leetcode

來源:互聯網
上載者:User
Question:

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. 題目大意就是把字串轉化成數,但是我看到這個題通過率很低,但是確是Eazy題,後來發現是因為要注意很多特殊情況 Algorithm:

1、數位第一個字元只能是‘+’、‘-’、數字

2、如果從第一個字元往後出現非數位字元,即返回之前的數

3、如果第一個字元是‘-’則返回負數

4、如果int數溢出即返回INT_MAX(正)或INT_MIN(負) Submitted Code:

class Solution {   //第一個數必須是‘+’或‘-’或數字    後面如果再出現不在0~9的數,直接返回前面的數public:    int myAtoi(string str) {        if(str.empty())return 0;        long long int res=0;        int flag=1;  //flag為正負標誌位        int i=0,j=0;        while(str[i] == ' ')            i++;        if(str[i] == '+')            i++;        else if(str[i] == '-')        {            i++;            flag = -1;        }        j=i;        for(j=i;j<str.size();j++)        {            if(str[j]>='0' && str[j]<='9')            {                res=res*10+(str[j]-'0');                if(res>INT_MAX)                    return flag>0 ? INT_MAX : INT_MIN;            }            else if(str[j]<'0' || str[j]>'9')                return flag>0 ? res:(-1)*res;        }        return flag==1?res:(-1)*res;    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.