首页 > 其他 > 详细

【LeetCode】- String to Integer (字符串转成整形)

时间:2014-05-15 23:33:45      阅读:495      评论:0      收藏:0      [点我收藏+]

问题: ]

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"));
	}
}


【LeetCode】- String to Integer (字符串转成整形),布布扣,bubuko.com

【LeetCode】- String to Integer (字符串转成整形)

原文:http://blog.csdn.net/zdp072/article/details/25913563

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!