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; }};