[算法]String to Integer(atoi)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[算法]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.

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)的主要内容,如果未能解决你的问题,请参考以下文章

Kotlin实现LeetCode算法题之String to Integer (atoi)

LeetCode-面试算法经典-Java实现008-String to Integer (atoi) (字符串转成整数)

LeetCode-8-String to Integer (atoi)

No.008:String to Integer (atoi)

String to Integer (atoi)

8. String to Integer (atoi)