string to int in Java


  • 0
    Z
    class Solution {
        public int myAtoi(String str) {
            if(str==null || str.length()==0) return 0;
            str = str.replaceAll("^(\\s|\t|\r|\n)+","") ; //trim left
            long result = 0;
            int flag = 1;
            for(int i = 0;i<str.length();i++){
                char temp = str.charAt(i);
                if(i==0 && temp=='-'){
                    flag = -1;
                }else if(i==0 && temp=='+'){
                    flag = 1;
                }else if(Character.isDigit(temp)){
                    result = 10 * result + (temp-'0');
                    if(result>Integer.MAX_VALUE && flag==1){
                        result = Integer.MAX_VALUE;
                        break;
                    }else if(result>Integer.MAX_VALUE && flag==-1){
                        result = Integer.MIN_VALUE;
                        break;
                    }
                }else{
                    break;
                }
            }
            if(flag * result < 0){
               result = flag * result;
            }
            return (int)result;
        }
    }
    

Log in to reply
 

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