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

String to Integer (atoi)

时间:2014-12-03 23:09:05      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

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 atoi(const char *str) {
        int sign = 1, base = 0, i = 0;
    while (str[i] ==  ) { i++; }
    if (str[i] == - || str[i] == +) {
        sign = 1 - 2 * (str[i++] == -); 
    }
    while (str[i] >= 0 && str[i] <= 9) {
        if (base >  INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - 0 > 7)) {
            if (sign == 1) return INT_MAX;
            else return INT_MIN;
        }
        base  = 10 * base + (str[i++] - 0);
    }
    return base * sign;
    }
};

 

String to Integer (atoi)

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/code-swan/p/4141315.html

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