8. String to Integer (atoi)

来源:互联网 发布:照片冲印排版软件 编辑:程序博客网 时间:2024/06/07 15:02

 问题来源:https://leetcode.com/problems/string-to-integer-atoi/

 问题描述: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.

    我的代码(9ms):

1)首先我们需要理解题目的意思,一句话就是实现atoi函数,但是根据提示其实包含了几个条件:字符串的输入格式 以及 最后结果的溢出判断

2)字符串的输入格式:首先除了数字和‘+’ ‘-’两个符号其他符号肯定不算入int的考虑范围,所以我们所需要转换的字符串第一个字符一定是‘+’ ‘-’ 或者是数字(所以前期需要进行空格的处理,注意如果需要的字符串的前缀不是空格,返回都结果为0 例如(+++1或者!-1)); 其次除了前缀部分,后缀一旦碰到不是数字的字符,立即跳出得到结果:例如“1+111”返回结果为1。

3)结果的溢出判断:由于规定函数返回的为int类型(范围是INT_MIN(-2147482648)到MIN_MAX(2147482648))超过的范围归为最大最小值,所以直接利用long long储存即可。

int myAtoi(string str) {if (str.length() == 0)return 0;long long res = 0;int sign = 1;int i = 0;while (str[i] == ' '){i++;}if (str[i] == '+'){i++;}else if (str[i] == '-'){sign = -1;i++;}for (int j = i; j < str.length(); j++){int temp = (str[j] - '0');if (temp >= 0 && temp <= 9){res = res * 10 + temp;if (res > INT_MAX)return sign > 0 ? INT_MAX : INT_MIN;//防止溢出}else{break;}}res *= sign;return (int)res;}

  其实C++有更为简便的函数可以实现该功能,不过在运行速度(leetcode通过测试为13ms)上面有所差异:

int myAtoi(string str) {if (str.find('0') == -1 && str.find('1') == -1 && str.find('2') == -1 && str.find('3') == -1 && str.find('4') == -1 && str.find('5') == -1 && str.find('6') == -1 && str.find('7') == -1 && str.find('8') == -1 && str.find('9') == -1)return 0;//不含数字直接返回0istringstream iss(str);//绑定strint num;iss >> num;//转化为int(空格会成为字符串的内部分界)return num;}

  关于所使用的istringstream类的使用之后再详细总结一下吧~


0 0
原创粉丝点击