LeetCode-String to Integer (atoi)

题目: https://oj.leetcode.com/problems/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.

分析,本题注意点:

1) 空字符串

2) 正负号

3) 非法字符

4)越界,应返回最大值、最小值

源码:Java版本
算法分析:时间复杂度O(n),空间复杂度O(1)

public class Solution {
	public int atoi(String str) {
		int i = 0;
		if (str.length() == 0) {
			return 0;
		}
		while (i < str.length() && str.charAt(i) == ' ') {
			i++;
		}
		int sign = 1;
		if (str.charAt(i) == '+') {
			i++;
		} else if (str.charAt(i) == '-') {
			i++;
			sign = -1;
		}

		int number = 0;
		while (i < str.length()) {
			if (str.charAt(i) < '0' || str.charAt(i) > '9') { //illegal
				return sign * number;
			}
			if (Integer.MAX_VALUE / 10 < number
					|| (Integer.MAX_VALUE / 10 == number 
					    && (str.charAt(i) - '0') > Integer.MAX_VALUE % 10)) {
				return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
			}
			number = 10 * number + str.charAt(i) - '0';
			i++;
		}
		return sign * number;
	}
}

你可能感兴趣的:(LeetCode)