8. String to Integer (atoi) LeetCode题解

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.

Subscribe to see which companies asked this question.

题意:

实现atoi函数,即将一个字符串转换为整型变量;

如果是初次做这个题,建议还是看一下转换要求,毕竟坑比较多;

几个坑如下:

1. 字符串可能包含一堆前导的空格符,然后是可选的正负号,最后是数字;

2. 数字时候可能包含一些非数字的字符,但不影响转换结果(只转换前面的部分);

3. 如果第一串非空序列不合法,或者根本不存在,则不进行转换(返回0);

4. 如果越界则返回范围内最大值(INT_MAX或者INT_MIN);


题解:

注意以上4点即可

Code【Java】

public class Solution {
    public int myAtoi(String str) {
    	// 检查是否为null
    	if (str == null) {
    		return 0;
    	}
    	// 去除前导以及后置的空格
        str = str.trim();
        if (str.length() == 0) {
        	return 0;
        }
        // 得到正负号
        int sign = (str.charAt(0) == '-') ? -1 : 1;
        // 生成数字
        int ans = 0;
        for (int i = (str.charAt(0) == '+' || sign == -1) ? 1 : 0;
        	 i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9';
        	 ++i) {
        	// 计算当前数位
        	int digit = sign * (str.charAt(i) - '0');
        	if (sign ==  1 && (Integer.MAX_VALUE - digit) / 10 < ans ||
        		sign == -1 && (Integer.MIN_VALUE - digit) / 10 > ans) {
        		return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        	}
        	ans = ans * 10 + digit;
        }
        // 返回结果
        return ans;
    }
}

Code【C++】

class Solution {
public:
    int myAtoi(string str) {
	    // 寻找第一个非0值
    	size_t pos = str.find_first_not_of(' ');
    	if (pos == string::npos) {
    		return 0;
    	}
        // 得到正负号
        int sign = (str[pos] == '-') ? -1 : 1;
        // 生成数字
        int ans = 0;
        for (size_t i = (str[pos] == '+' || sign == -1) ? pos + 1 : pos;
        	 i < str.length() && str[i] >= '0' && str[i] <= '9';
        	 ++i) {
        	// 计算当前数位
        	int digit = sign * (str[i] - '0');
        	if ((sign ==  1 && (INT_MAX - digit) / 10 < ans) ||
        		(sign == -1 && (INT_MIN - digit) / 10 > ans)) {
        		return (sign == 1) ? INT_MAX : INT_MIN;
        	}
        	ans = ans * 10 + digit;
        }
        // 返回结果
        return ans;
    }
};


猜你喜欢

转载自blog.csdn.net/baidu_23318869/article/details/71703580