Tuesday, July 21, 2015

String to Integer(atoi)

String to Integer(atoi)

15%
Accepted
Implement function atoi to convert a string to an integer.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
Have you met this question in a real interview? 
Yes
Example
"10" => 10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1
public class Solution {
    /**
     * @param str: A string
     * @return An integer
     */
    public int atoi(String str) {
        // write your code here
        if(str == null || str.length() == 0) return 0;
        str = str.trim();
        int sign = 1;
        int start = 0;
        if(str.charAt(0) == '-' || str.charAt(0) == '+'){
            sign = str.charAt(0) == '-' ? -1 : 1;
            start = 1;
        }
        int res = 0;
        for(int i = start; i < str.length(); i++){
            char c = str.charAt(i);
            if(c >= '0' && c <= '9'){
                if((c - '0') > Integer.MAX_VALUE - res * 10){
                    return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                res = res * 10 + (c - '0');
            } else {
                break;
            }
        }
        return sign * res;
    }
}

No comments:

Post a Comment