8. String to Integer (atoi)

来源:互联网 发布:linux显示行数 编辑:程序博客网 时间:2024/06/07 14:30

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.

解题思路:这道题不能说是一道算法题,应该是道语法题,它的核心点在于让你去考虑各种边界情况,其实就分为3种:首字符是否为空格,是否为+,-号,是否为数字; 下一步呢就是要考虑处理这三种情况的优先级,假设一个合法integer的字符串s,s首字符无论是space,还是 +/-,数字都是合法的,但是如果首字符是数字,那么后面的space,+/-是可以不处理的,所以优先级的话space,+/-是高于数字的,因为只有space和+/-在数字前面时,才需要去考虑;接下来就是判断space和+/-的优先级,如果space在+/-的前面,则需要消除空格,如果是+/-后面有空格,则是不合法的,不用考虑,所以space的优先级最高,需第一个考虑;

代码如下:

class Solution {public:    int myAtoi(string str) {        if (str.size() == 0) return 0;            int i = 0;    long int st = 0;    char f='+';    while (isspace(str[i]) != 0) {    i++;    }    if (i == str.size()) return 0;    if (str[i] == '+' || str[i] == '-') {    f = str[i]; i++;    }    while (isdigit(str[i]) != 0) {    st = st * 10 + (str[i] - '0');        i++;    if(st > INT_MAX){        if (f == '+'){        return INT_MAX;      }else{        return INT_MIN;     }        }    }    if (f == '+') {    return st;    }else{    return -st;    }    }};

运行结果:


原创粉丝点击