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

[LeetCode]41. String to Integer(atoi)字符串转整数

时间:2015-10-25 19:09:49      阅读:184      评论: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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

 

解法:不看requirements真写不出可以Accepted的来。主要考虑以下几点:

(1)输入空字符串:输出0;

(2)输入字符串最前面有若干个空格:去掉前面的空格;

(3)输入字符串的第一个非空格字符为正负号:输出结果对应改变;

(4)输入字符串除正负号外的第一个字符不是有效字符(‘0’到‘9’之间),输出0;

(5)输入字符串第一个有效字符后存在无效字符:直接截取前面的有效字符转换输出;不需要考虑科学计数法的e/E,或者小数点;

(6)输入字符串所表示的数字超出整型所表示的范围:输出INT_MAX或者INT_MIN。

class Solution {
public:
    int myAtoi(string str) {
        int n = str.size();
        if (n <= 0) return 0; //输入空串
        
        int i = 0, res = 0;        
        while (i < n && str[i] ==  ) ++i; //去除开头的空格        
        bool isNegative = false;
        if (i < n && (str[i] == - || str[i] == +)) //判断第一个字符是否是正负号
            if (str[i++] == -) isNegative = true;
        if (i < n && (str[i] < 0 || str[i] > 9)) return 0; //判断第一个字符是否合法
        
        while (i < n && str[i] >= 0 && str[i] <= 9) //转换为整数
        {
            if (res > INT_MAX / 10 || (res == INT_MAX / 10 && str[i] - 0 >= 8)) //是否超出最大最小值
                return isNegative ? INT_MIN : INT_MAX;
            res = res * 10 + str[i] - 0;
            ++i;
        }        
        return isNegative ? -res : res;
    }
};

[LeetCode]41. String to Integer(atoi)字符串转整数

标签:

原文地址:http://www.cnblogs.com/aprilcheny/p/4909169.html

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