String to Integer (atoi) Problem Solution in Java
Tags: problemsolving, programming, java, leetcode
Published: 2022-05-06 15:04:45

As simple as it may sound, our goal in this problem is to convert a string (that might or might not contain numbers) into an integer. The trick is to keep into consideration ALL possible cases, which are a lot. I recommend that you list them down in front of you while you're solving the problem so that you don't get confused.


**Leetcode's problem definition**

![Problem Definition](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yiojws72zu3xi434e8x5.png)


![Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/swytrnmgtqfnvzqydpz7.png)
![Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bp2azfazfh8ry7rt6r99.png)
![Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xtlehx1hnzh9qztzd3rg.png)


**My Approach**

1. I created an empty string "actual" where I would extract the numbers to be converted from the whole string. (To avoid confusion)

2. Looping through the string, all whitespaces are ignored. However, if the current iterator points at a number and the next character is a whitespace, then we need to BREAK from the loop.

3. If we meet a '+' or a '-' sign, we need to check whether 'actual' string is empty or not. Because if it isn't, then this sign is garbage and we'll break from the loop again. If it is empty, however, we store the sign.

4. After we've looped through the whole string, we need to check whether we found any numbers or not, that is, if our "actual" string is not empty. If it is empty, we'll just return 0.

5- If the first character in "actual" is a negative sign, then set our sign variable to -1.

6- Now loop through the rest of the characters in "actual" and use *Horner's rule* to convert the whole number to integer.

7- Check if the number lies within the 32-bit range. 

(Integer.MIN_VALUE <= num <= Integer.MAX_VALUE)

    public int myAtoi(String s) {
       if(s == null || s.length()==0)
           return 0;
        
       String actual = "";
       long num = 0;
       long sign = 1;
       for(int i = 0 ; i < s.length() ; i++){
           if(s.charAt(i)!=' '){
               if( actual.length() == 0 && i+1 < s.length()
                  && (s.charAt(i) == '-' || s.charAt(i) == '+') 
                  && Character.isDigit(s.charAt(i+1)))
                   actual += s.charAt(i);
               
               else if(!Character.isDigit(s.charAt(i)))
                   break;
               else if(Character.isDigit(s.charAt(i)))
                   actual += s.charAt(i);
               
               if(i+1 < s.length() && s.charAt(i+1)==' ')
                   break;
               
           }
       }
        
      if(actual.length() == 0)
          return 0;
      if(actual.charAt(0) == '-')
          sign = -1;
        
      for(int i=0; i<actual.length(); i++){
          if(Character.isDigit(actual.charAt(i))){
              num = num*10 + (actual.charAt(i) - '0');
              if(num*sign >= Integer.MAX_VALUE)
                  return Integer.MAX_VALUE;
              else if( num*sign <= Integer.MIN_VALUE)
                  return Integer.MIN_VALUE;
          }
      }
        
     return (int) (num*sign);
    }


**Feel free to reach out to me and let me know what you think!**
[LinkedIn](https://www.linkedin.com/in/shaimaa-hossam-367362164/)
[Github](https://github.com/ShaimaaHossam)
[Medium](https://medium.com/@shaimaahossam96)