首页 > 代码库 > leetcode.8---------------String to Integer (atoi)

leetcode.8---------------String to Integer (atoi)

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.

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.

本文提供2种方法,更多方法请看https://oj.leetcode.com/discuss/oj/string-to-integer-atoi

1.貌似这种方法也可以被AC.Runtime: 19 ms  原文链接:https://oj.leetcode.com/discuss/13704/my-simple-simple-solution

class Solution {
public:
    int atoi(const char *str) {
        if(*str == '\0') return 0;
        string s(str);
        istringstream iss(s);
        int n;
        iss>>n;
        return n;
    }
};


2.常用的方法,在线AC   Runtime: 14 ms

<pre name="code" class="cpp">class Solution {
public:
	// Start typing your C/C++ solution below
	// DO NOT write int main() function
	int atoi(const char *str)
	{
		if (str == NULL)
			return 0;

		int i = 0;
		while (str[i] == ' ') 
			i++;

		if (str[i] == '\0')
			return 0;
	
		int sign = 1;
		long long ans = 0;
		if (str[i] == '+' || str[i] == '-')
		{
			if (str[i++] == '-')
				sign = -1;
		}

		while (str[i] >= '0' && str[i] <= '9')
		{
			ans = ans * 10 + str[i] - '0';
			if (ans * sign > INT_MAX)
				return INT_MAX;
			if (ans * sign < INT_MIN)
				return INT_MIN;
			i++;
		}
		return ans * sign;
	}
};



leetcode.8---------------String to Integer (atoi)