Wednesday, January 7, 2015

LeetCode 8: 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.
public class Solution {
    public int atoi(String str) {
        // The difficulty of this question is that we should consider multiple special cases.
        // Case 1. The first character may be '+' or '-'
        // Case 2. Larger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE
        double result = 0; // In case of 'Case 3' (Note: 'long' type may not handle this number.)
        
        // Remove leading or trailing white spaces
        String s = str.trim();
        
        int n = s.length();
        boolean numBegin = false; // If has already counting number (including '+' and '-')
        boolean positive = true; // Positive or negative number (Note: abs(MAX_VALUE) != abs(MIN_VALUE))
        
        for (int i = 0; i < n; i++)
        {
            char c = s.charAt(i);
            
            if (c>='0' && c<='9')
            {
                result = result*10 + (c-'0');
                
                if (!numBegin)
                    numBegin = true;
            }
            // Case 1
            else if (c=='+' && !numBegin)
                numBegin = true;
            else if (c=='-' && !numBegin)
            {
                positive = false;
                numBegin = true;
            }
            else
                break;  
        }
        
        // Case 2
        if (positive)
        {
            if (result > Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
            else
                return (int)result;
        }
        else
        {
            result = -1*result;
            
            if (result < Integer.MIN_VALUE)
                return Integer.MIN_VALUE;
            else
                return (int)result;
        }
    }
}

No comments:

Post a Comment