LeetCode – String to Integer (atoi) (Java)

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;
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Rory

    Do not need this part

    // handle max and min

    if (result > Integer.MAX_VALUE)

    return Integer.MAX_VALUE;

    if (result < Integer.MIN_VALUE)

    return Integer.MIN_VALUE;

  • Renzo

    Solution in 11 lines of Python:https://github.com/renzon/code_interview_training/blob/master/string_to_int.py
    The good thing is that for integer I don’t have to worry once they are arbitrary large in Python (not arbitrary, but as long as it fit in your memory)

  • joseph

    Really should check the string length after doing the trim(), in case it was a string of just white spaces.

  • Peng

    I think the overflow check should be placed within for loop to attach this problem

  • Arnaud Hebert

    Why are we multiplying by 10: result = result * 10 ?

  • lily

    well,if the str is very very very big,such as it is bigger than long,how can you handle this?

  • he could use :
    Character.getNumericValue(str.charAt(i))

  • Chris

    Why the sign is not always supposed to be at the beginning of the string? Please give a example? Thank you.

  • sebastian

    hi is doing that because charAt return a char so you can’t sum a char, you need a way to convert to integer one choice is that and only is charAt(pos) – 48

    Bye.

  • armandm

    why are you substracting ” to the char
    ?

  • uee

    The sign is not always supposed to be at the beginning of the string. And you also didn’t consider the situation that other character show in the string.