-
要求
手动实现系统函数atoi的功能 注意的条件: (1)空串 (2)不合法的字符串,比如"words and 987" "+-12" "+ 32" “ ”等 ps: 确实如dalao所讲,所有的坑只有自己踩进去才会想到
-
代码
#include<iostream> #include<cstdio> #include<cmath> #include<vector> #include<stack> #include<cstring> using namespace std; long long myatoi(string str) { int flag = 1; int len = str.length(); int count = 0; long long ans = 0; if(str.size() == 0) return 0; int i = 0; while(str[i++] == ' '){ count++; } if(str[count] == '+'){ if(!(str[count+1] >= '0' && str[count+1] <='9')) return 0; flag = 1; count++; } if(str[count] == '-'){ if(!(str[count+1] >= '0' && str[count+1] <='9')) return 0; flag = -1; count++; } for(i = count; i < len; ++i) { if(str[count] < '0' || str[count] >'9'){ ans = 0; break; } else if(str[i] >= '0' && str[i] <= '9'){ ans = ans*10 + (str[i]-'0'); if(ans*flag <= INT_MIN){ ans = -1 * INT_MIN; break; } else if(ans*flag >= INT_MAX){ ans = INT_MAX; break; } } else if(str[i] < '0' || str[i] >'9' || str[i] == '.') { break; } } return ans*flag; } int main() { string str; while(getline(cin,str)){ //getline()可以读取空字符串、空格 int res = myatoi(str); cout<<res<<endl; } return 0; }
【LeetCode 8】字符串转换整数 (atoi)
最新推荐文章于 2021-10-12 08:30:28 发布