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.

spoilers alert... click to show requirements for atoi.

public class Solution {
    public int atoi(String str) {
        String trimStr = str.trim();
		int len = trimStr.length();
		if(len == 0) return 0;
		long result = 0;
		boolean negative = false;
		int start = 0;
		if(trimStr.charAt(0) == '-' || trimStr.charAt(0) == '+'){
			negative = (trimStr.charAt(0) == '-');
			++start;
		}
		while (start < len){
			if(trimStr.charAt(start) >= '0' && trimStr.charAt(start) <='9'){
				result = (result * 10) + (trimStr.charAt(start) - '0');
				
				//compare with the max integer and min integer
				if(negative && result >= (long)Integer.MAX_VALUE + 1) //do not forget the conversion
				    return Integer.MIN_VALUE;
				if(!negative  && result >= Integer.MAX_VALUE)
					return Integer.MAX_VALUE;
			}
			else //a character not a digit
				break;
			++start;
		}
		if(negative)
		    result *= (-1);
		return (int) result;
    }
}

  

  

posted @ 2014-02-23 01:10  Averill Zheng  阅读(146)  评论(0编辑  收藏  举报