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.

public class Solution {
    public int myAtoi(String str) {
        if (str == null) {
            return 0; 
        }
        /*
         * trim() returns a copy of the string, with leading 
         * and trailing whitespace omitted. 
         */
        str = str.trim(); 
        if (str.length() == 0) {
            return 0; 
        }
        
        int sign = 1; //sign of the number 
        int index = 0; //record the digit of the number 
        
        if (str.charAt(index) == '+') {
            index++; 
        } else if (str.charAt(index) == '-') {
            sign = -1; 
            index++; 
        }
    
        long num = 0; //return value 
        for (; index < str.length(); index++) {
            if (str.charAt(index) < '0' || str.charAt(index) > '9') 
                break; 
            num = num * 10 + (str.charAt(index) - '0' );  //update 
            if (num > Integer.MAX_VALUE) {
                break; 
            }
        }
        if (num*sign >= Integer.MAX_VALUE) {
            return Integer.MAX_VALUE; 
        }
        if (num*sign <= Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;  
        }
        return (int) num*sign; 
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s