Monday, February 3, 2014

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.

Solution:

public class Solution {
    public int atoi(String str) {
        int characterPointer = 0;
        boolean isNegative = false;
        long solution = 0;
        while(characterPointer<str.length() && Character.isWhitespace(str.charAt(characterPointer)))
            characterPointer++;
        if (characterPointer==str.length())
            return 0; //String that is empty or only white spaces
        if(str.charAt(characterPointer)=='-')
        {
            isNegative = true;
            characterPointer++;
        }
        else if(str.charAt(characterPointer)=='+')
        {
            isNegative = false;
            characterPointer++;
        }
            
        for (; characterPointer<str.length(); characterPointer++)
        {
            if(!Character.isDigit(str.charAt(characterPointer)))
                break;
            solution *= 10;
            solution += Character.getNumericValue(str.charAt(characterPointer));
        }
        if(!isNegative && solution> Integer.MAX_VALUE)
            return Integer.MAX_VALUE;
        if(isNegative && -1*solution < Integer.MIN_VALUE)
            return Integer.MIN_VALUE;
        return isNegative ? (int)(-1*solution) : (int)solution;
        
    }
}

No comments :

Post a Comment