a solution which is easy to understand


  • 0
    C
    public class Solution {
        public int myAtoi(String str) {
            if(str.length() == 0 ) {
    			return 0;
    		}
    		str = str.trim();
    		char[] strs = str.toCharArray();
    		boolean isPos = true;
    		int sum = 0;
    		int start = 0;
    		if(strs[0] == '-') {
    			isPos = false;
    			start = 1;
    		}
    		if(strs[0] == '+') {
    			isPos = true;
    			start = 1;
    		}
    		for(int i = start;i<strs.length;i++) {
    			if(strs[i]>='0' && strs[i]<='9') {
    				if(isPos) {
    				    if(i+1-start<=10) {
    						if((Integer.MAX_VALUE-sum*10)<strs[i]-'0')
                                                    {
    							return Integer.MAX_VALUE;
    						}
    					}else {	
    						return Integer.MAX_VALUE;
    					}
    				}
    				if(!isPos ) {
    					if(i+1-start<=10) {
    						if((sum*10+Integer.MIN_VALUE)>
                                                            -strs[i]+'0') {
    							return Integer.MIN_VALUE;
    						}
    					}else {
    						return Integer.MIN_VALUE;
    					}
    				}
    				sum = sum*10;
    				sum = sum +(strs[i]-'0');
    			}else {
    				return isPos?sum:-sum;
    			}
    		}
    		return isPos?sum:-sum;
        }
    }
    

Log in to reply
 

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