Atoi

Implement atoi to convert a string to an integer.

Example :

Input : "9 2704"
Output : 9

Note: There might be multiple corner cases here. Clarify all your doubts using “See Expected Output”.

Questions:

Q1. Does string contain whitespace characters before the number? A. Yes

Q2. Can the string have garbage characters after the number? A. Yes. Ignore it.

Q3. If no numeric character is found before encountering garbage characters, what should I do? A. Return 0.

Q4. What if the integer overflows? A. Return INT_MAX if the number is positive, INT_MIN otherwise.

Warning : DO NOT USE LIBRARY FUNCTION FOR ATOI. If you do, we will disqualify your submission retroactively and give you penalty points.

class Solution {
    public int atoi(final String s) {
        String str = s.trim();
        if (str.length() == 0)
            return 0;

        if (str.charAt(0) == '+' || str.charAt(0) == '-' || (str.charAt(0) >= '0' && str.charAt(0) <= '9')) {
            boolean flag = true;
            int pointer = 0;
            if (str.charAt(0) == '+') {
                flag = true;
                pointer = 1;
            } else if (str.charAt(0) == '-') {
                flag = false;
                pointer = 1;
            }
            while (pointer < str.length() && str.charAt(pointer) == '0') 
                pointer++;

            long ans = 0;
            while (pointer < str.length() && (str.charAt(pointer) >= '0' && str.charAt(pointer) <= '9')) {
                ans = ans * 10 + (int) (str.charAt(pointer) - '0');
                if (flag) {
                    if (ans > Integer.MAX_VALUE)
                        return Integer.MAX_VALUE;
                } else {
                    if ((-ans) < Integer.MIN_VALUE)
                        return Integer.MIN_VALUE;
                }
                pointer++;
            }
            if (flag)
                return (int) ans;
            else
                return (int) (-ans);
        } else
            return 0;
    }
}

Last updated