[LeetCode] String to Integer (atoi)

xiaoxiao2021-02-28  6

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.

要解决这个问题最关键的部分就在于要考虑到所有可能的输入并从中判断出合法的输入。

首先如果字符串开头有空白则需要把空白部分给跳过。

因为atoi函数是转换字符串开头部分的数字为整型,因此合法的输入字符串必须开头的部分为合法的数字,而且因为要求输出整型,所以可以将小数点作为不合法的字符,此外还要考虑开头为正负号的情况。例如“-1235.134asdf”, 处理后应变为"-1235"。

如果判断字符串不符合转换整型的条件,则返回0.

得到处理完后的字符串后就要将其转换为数字了,可以通过多项式转换计算整型的值,也可以通过stringstream直接将字符串转为数字,但stringstream的效率可能会比较低一些,但是考虑到整型数本身位数就不多,可以忽略略微的效率问题,而且stringstream的实现也简单得多,更加方便,于是我便采用了stringstream的方法。

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; } } };

转载请注明原文地址: https://www.6miu.com/read-1100084.html

最新回复(0)