题目:
答案(c++):
直接用库
class Solution {
public:int myAtoi(string str) {int flag = 0;for (char a : str){if (a == ' ') flag++;}if (flag == str.size()) return 0;stringstream ss;int result;ss << str;ss >> result;return result;}
};
结果:
网上较好的答案:
class Solution {
public:int myAtoi(string str) {int le = str.length(), i = 0, j = 0, sign = 1, flag = 1, flag2 = 1;long k = 0;for(i = 0; i < le; i++){if(flag < 0 || (not flag && str[i] == ' ')) return 0;else if((str[i] > '0' && str[i] <= '9'))break;else if(str[i] == '-'){sign = -1;flag -= 1;}else if(str[i] == '+' || (flag && str[i] == '0'))flag -= 1;else if(str[i] != ' ' && (str[i] < '0' || str[i] > '9'))return 0;}for(j = i; j < le && str[j] >= '0' && str[j] <= '9'; j ++){if(j-i > 10){k = 2147483648;break;}k *= 10;k += str[j]-'0';}k *= sign;if(k > 2147483647)return 2147483647;if(k < -2147483648)return -2147483648;return k;}
};