String to Integer (atoi) Implementation


  • 0
    P

    As it is not clearly mentioned in the problem statement, the following conditions/cases should be considered before solving this problem:

    Check if the string

    • Is null or Empty
    • Contains white spaces
    • Has +/- sign at the beginning

    Then

    • Form the number
    • Handle max and min
    class Solution {
        public int myAtoi(String str) {
            //chk if null or empty
            if(str == null || str.length()<1){
                return 0;
            }
            
            //removing white spaces
            str = str.trim();
            
            //checking positive or negative
            int flag = '+';
            int i=0;
            
            if(str.charAt(i) == '-'){
                flag = '-';
                i++;
            }
            else if(str.charAt(i) == '+'){
                i++;
            }
            
            //form the number from string
            double result = 0;
            
            while(str.length()>i && str.charAt(i)>='0' && str.charAt(i)<='9'){
                result = result*10 + (str.charAt(i)-'0');
                i++;
            }
            
            if(flag == '-'){
                result = -result;
            }
            
            //handle max and min i.e. check limits as we are returning int
            if(result >= Integer.MAX_VALUE){
                result = Integer.MAX_VALUE;
            }
            else if(result <= Integer.MIN_VALUE){
                result = Integer.MIN_VALUE;
            }
            
            return (int)result;
        }
    }
    

  • 0
    D

    '''
    try{
    str=str.trim();
    if(str.contains("-")&&str.contains("+"))
    return 0;
    int q=0;
    for(int i=0;i<str.length();i++){
    if(Character.isLetter(str.charAt(i))||Character.isWhitespace(str.charAt(i))){
    q=i;
    break;
    }
    }
    if(q>0)
    str=str.substring(0,q);
    Double x = new Double(String.valueOf(str));
    if(x>Integer.MAX_VALUE)
    return Integer.MAX_VALUE;
    else if(x<Integer.MIN_VALUE)
    return Integer.MIN_VALUE;

            return x.intValue();
        }
        catch(Exception e){
            return 0;
        }
    

    '''


Log in to reply
 

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