首页 > 编程语言 > 详细

[算法]String to Integer(atoi)

时间:2016-02-17 00:52:18      阅读:210      评论:0      收藏:0      [点我收藏+]

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.

Analysis

The following cases should be considered for this problem:

1. null or empty string
2. white spaces
3. +/- sign
4. calculate real value
5. handle min & max

Java Solution

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

[算法]String to Integer(atoi)

原文:http://www.cnblogs.com/xiaomoxian/p/5194118.html

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