My Java solution


  • 0
    O
    public class Solution {
        public int myAtoi(String str) {
            int i, size = str.length(), sign = 0;
            double  result = 0;
            char ch;
            for(i = 0; i < size; i++) {
                ch = str.charAt(i);
                if (ch == ' ' && sign != 0) {
                    return (int)result;
                }
                if (ch == '-' && sign == 0) {
                    sign = -1;
                } else if (ch == '+' && sign == 0) {
                	sign = 1;
                } else if ((ch == '+' || ch == '-') && sign != 0) {
                    return (int)result;
                }
                if (ch >= '0' && ch <= '9') {
                    if (result == 0) {
                    	if (ch != '0' && sign == 0) {
                    	    sign = 1;
                    	}
                        result = sign * (ch-48);
                    } else {
                        if (result*10 + (ch-48) >= Integer.MAX_VALUE) {
                            return Integer.MAX_VALUE;
                        }
                        if (result * 10 + (ch-48) <= Integer.MIN_VALUE) {
                            return Integer.MIN_VALUE;
                        }
                        result = result*10 + sign*(ch-48);
                    }
                }
                if ((ch < '0' || ch > '9') && ch != ' ' && ch != '-' && ch != '+') {
                    return (int)result;
                }
                
            }
            
            return (int)result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.