首页 > 代码库 > 【LeetCode】- String to Integer (字符串转成整形)

【LeetCode】- String to 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.

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.

[ 分析]

① 字符串为空或空字符串, 返回0;
② 忽略字符串前后空格;
③ 第一个字符如果为‘+‘或‘-‘先记住它, 接着往下读, 如果读到的是数字, 则开始处理数字, 如果为其他特殊字符, 停止读取, 返回结果;
④ 处理过程中, 如果转换出的值超出了int类型范围, 那么返回int的最大值或最小值.

[ 解法]

public class Solution {
	private final static int INT_MAX = 2147483647;
	private final static int INT_MIN = -2147483648;

	public int atoi(String str) {
		int i = 0, flag = 1; // flag为正负标记符
		long result = 0; // 转换之后可能变成long型
		
		if (str == null || str.length() == 0) {
			return 0; // step 1
		}
		
		char[] ch = str.trim().toCharArray();
		
		if (ch.length == 0) {
			return 0; // step 2
		}
		
		if (ch[i] == '+' || ch[i] == '-') {
			flag = ch[i++] == '+' ? 1 : -1; // step 3
		}

		while (i < ch.length && ch[i] >= '0' && ch[i] <= '9') {
			result = result * 10 + (ch[i++] - '0'); // '0'到'9' askii码为48~57
			if (result * flag < INT_MIN || result * flag > INT_MAX) {
				return result * flag < INT_MIN ? INT_MIN : INT_MAX; // step 4
			}
		}
		
		return (int) result * flag;
	}

	public static void main(String[] args) {
		System.out.println(new Solution().atoi("999"));
	}
}