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 myAtoi(String str) {
        double num = 0;
        str = str.trim();
        int digit = 0;
        boolean flag = false;
        for (int i = str.length()-1; i >= 0; i--) {
        	char ch = str.charAt(i);
        	if (ch<='9' && ch>='0') {
        		num += (ch-'0') * (int)Math.pow(10, digit);
        		digit++;
        	} else if (ch=='+' || ch=='-') {
        		if (flag) {
        			return 0;
        		}
        		flag = true;
        		if (ch=='-') {
        			num = -num;
        		}
        	} else {
        		num = 0;
        		flag = false;
        		digit = 0;
        	}
        }
        if (num > Integer.MAX_VALUE) {
        	return Integer.MAX_VALUE;
        }
        if (num <= Integer.MIN_VALUE) {
        	return Integer.MIN_VALUE;
        }
        return (int) num;
    }
}

 

你可能感兴趣的:(Integer)