標籤:
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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
spoilers alert... click to show requirements for atoi.
//沒有時間做最佳化,不過個人估計測試集中缺少例如1.2e、.123e4、123..1e3這些數位判斷
class Solution {public: int myAtoi(string str) { //判斷字串是否未定義或者為空白 if(""==str) return 0; bool sign=false,esign=false; int i=0,j=0,_sign=1,x=0,e=0; double num=0.0,tmp_num; for(i=0;i<str.length();i++) { if(!sign) //對字串初始部分進行處理 { if(‘ ‘==str[i]) continue; else if(‘+‘==str[i]) { sign=true; continue; }else if(‘-‘==str[i]) { sign=true; _sign=-1; continue; }else if(‘e‘==str[i]||‘E‘==str[i]) { return 0; } } sign=true; //初始部分處理完畢標記sign if(isdigit(str[i])) { if(!x) //無小數部分 { num=num*10+str[i]-‘0‘; }else //含小數部分 { num+=(str[i]-‘0‘)/pow(10,x); x++; } }else if(‘.‘==str[i]) { if(x) return _sign*num; //遇到小數點重複情況 else x++; }else if(‘e‘==str[i]||‘E‘==str[i]) { for(j=i+1;j<str.length();j++) { if(isdigit(str[j])) { e=e*10+str[j]-‘0‘; }else { break; } } break; //跳出字串迴圈 }else { num*=_sign; tmp_num=num*pow(10,e); if(tmp_num>INT_MAX||tmp_num<INT_MIN) { if(num>INT_MAX) return INT_MAX; else if(num<INT_MIN) return INT_MIN; else return (int)num; }else { return (int)tmp_num; } } } num*=_sign; tmp_num=num*pow(10,e); if(tmp_num>INT_MAX||tmp_num<INT_MIN) { if(num>INT_MAX) return INT_MAX; else if(num<INT_MIN) return INT_MIN; else return (int)num; }else { return (int)tmp_num; } }};
此處學習到str[i]是char,傳遞進入函數的時候需注意。
""是字串,‘‘是字元,亦需要注意;
最後num=str[i]-‘0‘,很巧妙啊,isdigit亦可以用此代替。
String to Integer (atoi)