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>

  1. uee on 2014-1-26

    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.

  2. armandm on 2015-3-11

    why are you substracting ” to the char
    ?

  3. sebastian on 2015-3-16

    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.

  4. Chris on 2015-3-29

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

  5. Taoufik Bdiri on 2015-4-11

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

  6. lily on 2015-4-14

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

  7. Arnaud Hebert on 2015-4-19

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

  8. Peng on 2015-4-24

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

  9. joseph on 2015-11-10

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

  10. Renzo on 2016-2-7

    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)

  11. Rory on 2016-3-28

    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;

  12. loyolakarl on 2016-6-3

    kj;ljdaLJD

    I am writing some code as said before lol. :)

  13. S├ękine Coulibaly on 2016-9-5

    I guess it mean for positive numbers, eg. 42.
    Obviously 42 is positive, and equals to +42, but there is no leading “+” sign.

  14. Brandon Donnelson on 2016-12-4

    Alternative solution.


    public int myAtoi(String str) {
    if (str == null || str.isEmpty()) {
    return 0;
    }

    str = str.trim();

    if (str.equals("-")) {
    return 0;
    }

    if (str.equals("+")) {
    return 0;
    }

    int signAdd = 0;
    boolean sign = false;
    long result = 0;
    for (int i = 0; i 1) {
    return 0;
    }
    }

    if (c == '-') {
    sign = true;
    } else if (c == '+') {
    sign = false;
    } else if (c >= '0' && c Integer.MAX_VALUE) {
    return Integer.MAX_VALUE;
    } else if (sign && result *-1 < Integer.MIN_VALUE) {
    return Integer.MIN_VALUE;
    }

    }

    if (sign) {
    result *= -1;
    }

    return (int) result;
    }

  15. Brenda Martis on 2017-2-5

    Why was double used for result?

Leave a comment

*