在LintCode上刷题,刷到一道atoi,以为很简单,轻松写完后发现测试用例简直丧心病狂。
也许是刚开始的思路就被局限了,于是硬着头皮走上“添砖加瓦”的道路(其实就是加点if-else),最后成功AC,代码如下:
int atoi(string &str) { int len = str.size(); int end = 0; long sum = 0; char dot_flag = 0; int dot_loc = 0; char minus_flag = 0; int error_char_cnt = 0; char MAX_flag = 0; for(int i=len-1; i>=0; --i) { if(str[i] == '.') { sum = 0; MAX_flag = 0; dot_flag = 1; dot_loc = i; continue; } else if(str[i] == '-') //-符号出现 { minus_flag = 1; if(i!=0 && str[i-1]!=' ') return 0; else break; } else if(str[i] == '+') //+符号出现 { if(minus_flag) return 0; error_char_cnt = len-i; if(i != 0 && str[i-1]!=' ') { sum = 0; MAX_flag = 0; } continue; } else if(str[i] == ' ') { error_char_cnt++; continue; } else if(str[i]<48 || str[i]>57) { error_char_cnt = len-i; sum = 0; MAX_flag = 0; continue; } if(dot_flag == 0) { if(MAX_flag == 0) sum += (str[i]-'0')*pow(10,len-1-i-error_char_cnt); if(sum > INT_MAX && MAX_flag==0) { sum = INT_MAX; MAX_flag = 1; } } else { if(MAX_flag == 0) sum += (str[i]-'0')*pow(10,dot_loc-1-i-error_char_cnt); if(sum > INT_MAX && MAX_flag==0) { sum = INT_MAX; MAX_flag = 1; } } } if(minus_flag == 1) { if(sum == INT_MAX) sum = INT_MIN; else sum *= (-1); } return sum; }
最新评论