yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #8 String to Integer (atoi) #139

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class Solution {
    public int myAtoi(String str) {
        if (str.length() == 0) {
            return 0;
        }

        int index = 0;

        while (index < str.length() && str.charAt(index) == ' ') {
            index++;
        }

        int sign = 1;
        //1 for positive, -1 for negative

        if (index >= str.length()) {
            return 0;
        }
        if (str.charAt(index) != '-' && str.charAt(index) != '+'&& !Character.isDigit(str.charAt(index))) {
            return 0;
        }
        else if (str.charAt(index) == '-') {
            sign = -1;
            index++;
        }
        else if (str.charAt(index) == '+') {
            index++;
        }

        int res = 0;
        while (index < str.length()) {
            if (!Character.isDigit(str.charAt(index))) {
                break;
            }

            if(Integer.MAX_VALUE/10 < res || Integer.MAX_VALUE/10 == res && Integer.MAX_VALUE %10 < str.charAt(index) - '0') {
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }

            res = res*10 + str.charAt(index) - '0';
            index++;
        }

        return res*sign;
    }
}

Dealing with EDGE cases. Good details to rememeber:

  1. after incrementing index, we should add
    if (index >= str.length()) {
            return 0;
        }

    to avoid " " case.

  2. a very good way to check the range on both negative and positive numbers is to check before adding the digit like this:
    if(Integer.MAX_VALUE/10 < res || Integer.MAX_VALUE/10 == res && Integer.MAX_VALUE %10 < str.charAt(index) - '0') {
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }