leetcode

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.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Cases to consider:

  • skip all starting whitespace
  • first + and - sign
  • negative overflow and positive overflow
public int atoi(String str) {
        if (str == null || str.isEmpty()) {
            return 0;
        }

        char[] cStr = str.toCharArray();
        int index = 0;
        // skip all whitespace
        while (index < cStr.length) {
            if (!Character.isWhitespace(cStr[index])) {
                break;
            }
            index = index + 1;
        }

        boolean isNegative = false;
        if (index < cStr.length) {
            if (cStr[index] == '-') {
                isNegative = true;
                index = index + 1;
            } else if (cStr[index] == '+') {
                index = index + 1;
            }
        }

        int number = 0;
        boolean isOverflow = false;
        while (index < cStr.length) {
            char current = cStr[index];
            // check digit
            if (!Character.isDigit(current)) {
                break;
            }
            long lNumber = number * 10l;
            if (lNumber>Integer.MAX_VALUE) {
                isOverflow = true;
                break;
            } else {
                number = number * 10;
            }
            lNumber = lNumber + (current - '0');
            if (lNumber>Integer.MAX_VALUE) {
                isOverflow = true;
                break;
            } else {
                number = number + (current - '0');
            }
            index = index + 1;
        }

        // "21474836488"
        if (isOverflow) {
            if (isNegative) {
                number = Integer.MIN_VALUE;
            } else {
                number = Integer.MAX_VALUE;
            }
        //-12345
        } else if (isNegative) {
            number = number * -1;
        }

        return number;
    }