码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】8. String to Integer (atoi)

时间:2016-09-10 11:31:52      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

虽然是个简单题,但是要考虑的细节挺多的,比如输入空串的话如何输出,输入有+,-号的话怎么办,如果遇到无效输入怎么办?数字溢出了该如何输出?如果遇到的是面试,最好都要弄清楚。

 

class Solution {
public:
    int myAtoi(string str) {
        if (str == "") return 0;
        int flag = 1;
        int res = 0;
        string::const_iterator iter = str.begin(); 

        while (*iter ==   && iter != str.end()) iter++;
        
        if (*iter == + || *iter == -){
            if (*iter == -) flag = -1;
            *iter++;
        } 

        while (iter!=str.end() && isValidNum(*iter)) {
            int tmp = *iter - 0;
            if (res > (INT_MAX - tmp) / 10 && flag == 1) return INT_MAX;
            if (res > (INT_MAX - tmp) / 10 && flag == -1) return INT_MIN;
            
            res = res * 10 + tmp;
            iter++;
        }
        return flag*res;
    }
    
    bool isValidNum(char c)
    {
        return c >= 0 && c <=9;
    }
};

 

【LeetCode】8. String to Integer (atoi)

标签:

原文地址:http://www.cnblogs.com/Doctengineer/p/5858896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!