Monday, January 29, 2018

[2018-Interview] String to Integer

Original question: https://leetcode.com/problems/string-to-integer-atoi/description/

My answer: Leverage the method to determine if number is overflow: http://yizheliu.blogspot.com/2018/01/2018-interview-reverse-string.html



class Solution {
    public int myAtoi(String str) {
        if (str == null || str.length() < 1) {
            return 0;
        }
        int sign = 1;
        int i = 0;
        while (str.charAt(i) == ' ') {
            i ++;
        }
        if (str.charAt(i) == '-') {
            sign = -1;
            i ++;
        } else if (str.charAt(i) == '+') {
            i ++;
        } 
        
        int res = 0;
        int temp = 0;
        while ( i < str.length() &&
            str.charAt(i) <= '9' &&
            str.charAt(i) >= '0') {
            temp = res * 10 + sign * Integer.valueOf(str.charAt(i) - '0');

            if ((temp / 10) != res) {// overflow
                if (sign > 0) {
                    return Integer.MAX_VALUE;
                } else {
                    return Integer.MIN_VALUE;
                }
            }
            res = temp;
            i ++;
        }
        return res;
    }
}

No comments:

Post a Comment