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

#8 String to Integer (atoi)

时间:2015-04-10 11:16:03      阅读:124      评论: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.

题目不难,一样要注意int的边界问题。

代码如下:

class Solution {
public:
    int atoi(string str) {
        if (str.size() == 0)
            return  0;
        bool sign = false;
        long long num = 0;
        string::const_iterator iter = str.begin();
        while (iter != str.end() && *iter ==  ){ ++iter; }
        if (iter == str.end())
            return 0;
        if (*iter == + || *iter == -){
            if (*iter == -)
                sign = true;
            iter++;
        }
        while (iter != str.end()){
            if (*iter >= 0&&*iter <= 9){
                num = num * 10 + *iter - 0;
                if (num > 2147483648){
                    num = 2147483648;
                    break;
                }
            }
            else
                break;
            ++iter;
        }
        if (sign == true)
            num = 0 - num;
        else if (num == 2147483648)
            num--;
        return num;
    }
};

 

#8 String to Integer (atoi)

标签:

原文地址:http://www.cnblogs.com/Scorpio989/p/4413790.html

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