# [LeetCode] String to Integer (atoi)

xiaoxiao2021-02-28  5

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.

class Solution { public: /*判断是否为合法字符*/ bool isLegal(char c) { if (c == '+' || c == '-' || (c >= '0' && c <= '9')) { return true; } return false; } /*判断是否为数字*/ bool isNum(char c) { if (c >= '0' && c <= '9') { return true; } return false; } int myAtoi(string str) { string num = ""; // 用于存储过滤后的字符串 bool flag = false; for (int i = 0; i < str.length(); i++) { if (isspace(str[i]) && flag == false) { // 利用isspace清除空白 continue; } else { flag = true; } if (!isLegal(str[i])) { break; } else { num += str[i]; // 如果字符合法则加入num字符串 } } if (!isNum(num[num.length() - 1])) { return 0; } else { stringstream ss; // 利用stringstream将字符串转换为整型 ss.str(num); int i; ss >> i; return i; } } };