【LeetCode】String to Integer (atoi) 解题报告

这道题在LeetCode OJ上难道属于Easy。可是通过率却比較低,究其原因是须要考虑的情况比較低,非常少有人一遍过吧。

【题目】

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.

【解析】

我预计没有多少人不看以下的要求就通过的吧!

这道题要求的 atoi 跟C++实现的不一样吧。比方我以为不符合要求的返回-1,而这道题要求返回0。

所以,有必要解释一下题目的要求:

1. 首先须要丢弃字符串前面的空格;

2. 然后可能有正负号(注意仅仅取一个,假设有多个正负号。那么说这个字符串是无法转换的,返回0。比方測试用例里就有个“+-2”);

3. 字符串能够包括0~9以外的字符,假设遇到非数字字符,那么仅仅取该字符之前的部分,如“-00123a66”返回为“-123”;

4. 假设超出int的范围,返回边界值(2147483647或-2147483648)。

综上,要求还是有点怪的,不看要求是非常难写对的,看了也不一定理解的对。

【Java代码】

public class Solution {
    public int atoi(String str) {

        // 1. null or empty string
        if (str == null || str.length() == 0) return 0;

        // 2. whitespaces
        str = str.trim();

        // 3. +/- sign
        boolean positive = true;
        int i = 0;
        if (str.charAt(0) == ‘+‘) {
            i++;
        } else if (str.charAt(0) == ‘-‘) {
            positive = false;
            i++;
        }

        // 4. calculate real value
        double tmp = 0;
        for ( ; i < str.length(); i++) {
            int digit = str.charAt(i) - ‘0‘;

            if (digit < 0 || digit > 9) break;

            // 5. handle min & max
            if (positive) {
                tmp = 10*tmp + digit;
                if (tmp > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            } else {
                tmp = 10*tmp - digit;
                if (tmp < Integer.MIN_VALUE) return Integer.MIN_VALUE;
            }
        }

        int ret = (int)tmp;
        return ret;
    }
}

參考 http://www.programcreek.com/2012/12/leetcode-string-to-integer-atoi/ ,代码例如以下:

public int atoi(String str) {
	if (str == null || str.length() < 1)
		return 0;

	// trim white spaces
	str = str.trim();

	char flag = ‘+‘;

	// check negative or positive
	int i = 0;
	if (str.charAt(0) == ‘-‘) {
		flag = ‘-‘;
		i++;
	} else if (str.charAt(0) == ‘+‘) {
		i++;
	}
	// use double to store result
	double result = 0;

	// calculate value
	while (str.length() > i && str.charAt(i) >= ‘0‘ && str.charAt(i) <= ‘9‘) {
		result = result * 10 + (str.charAt(i) - ‘0‘);
		i++;
	}

	if (flag == ‘-‘)
		result = -result;

	// handle max and min
	if (result > Integer.MAX_VALUE)
		return Integer.MAX_VALUE;

	if (result < Integer.MIN_VALUE)
		return Integer.MIN_VALUE;

	return (int) result;
}

代码看起来更简洁,可是第一种写法能够及时跳出循环。不用计算完了再推断是否越界。

时间: 2024-10-15 01:43:10

【LeetCode】String to Integer (atoi) 解题报告的相关文章

【LeetCode】String to Integer (atoi) 解题报告 (Java)

这道题在LeetCode OJ上难道属于Easy,但是通过率却比较低,究其原因是需要考虑的情况比较低,很少有人一遍过吧. [题目] 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 poss

[LeetCode] String to Integer (atoi) [7]

题目 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

leetcode——String to Integer (atoi) 字符串转换为整型数(AC)

mnesia在频繁操作数据的过程可能会报错:** WARNING ** Mnesia is overloaded: {dump_log, write_threshold},可以看出,mnesia应该是过载了.这个警告在mnesia dump操作会发生这个问题,表类型为disc_only_copies .disc_copies都可能会发生. 如何重现这个问题,例子的场景是多个进程同时在不断地mnesia:dirty_write/2 mnesia过载分析 1.抛出警告是在mnesia 增加dump

LeetCode——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 spe

[leetcode] [leetcode] 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 spe

leetcode - String to Integer (atoi) 字符串转整数

Implement atoi to convert a string to an integer. 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. 题目:实现字符串转整数 注意事项:考虑好各种可能的输入(坑); public class Solution

[LeetCode] 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 spe

[LeetCode] 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 spe

[LeetCode] 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 spe