Java Program To Write Your Own atoi()


atoi() function is used in C programming language and used to convert the string which is passed as the parameter to it into an integer value if the string is a valid integer otherwise it shows the undefined behavior. We will implement the atoi() function in the Java programming language.

Input

string str = "123"

Output

123

Explanation

We are given a string that represents a number so we have just got the same output.

Input

string str = "897c7"

Output

Invalid Input 

Explanation

The given string is not a valid integer, so we have given the corresponding output.

Input

string str = "-123" 

Output

-123

String is Valid

In this approach, we will assume the given string is the valid string and it contains only the digits and may contain a '-' character representing the number is the negative number.

This string will not contain any whitespaces in the starting, middle, or at the end of the string.

In this approach, first, we will get an integer to store the answer and another integer to mark whether the current number is negative or not.

If the first character is the minus symbol, we will mark the negative integer as -1 and traverse the string from the 1st index otherwise we will traverse from the 0th index.

At each index, we will multiply the current number by 10 to increase one decimal point and then add the current digit to it. Also, we will get the ASCII value by getting the current digit from the string, so we have to remove the ASCII value of the '0' from the current character.

At the end, we will return the final answer, let us see the complete code:

Example

public class Solution{    
   // function to convert the string to an integer 
   public static int atoi(String str){
      // Assuming the string is valid 
      int neg = 1; // checking for the negative number         
      if(str.charAt(0) == '-'){
         neg = -1;
      }
      int ans = 0; 
      int i = 0; 
      // if the number is the negative number then start from the next index 
      if(neg  == -1){
         i++;
      }        
      for(; i < str.length(); i++){
         ans = ans * 10 + str.charAt(i) - '0';
      }        
      ans =  ans* neg;
      return ans; // returning the answer 
   }    
   public static void main(String []args){
      String str = "-354663"; // given string         
      // calling the function 
      int ans = atoi(str);        
      // printing the answer
      System.out.printf("The value of the current number is %d", ans);
   }
}

Output

The value of the current number is -354663

Time and Space Complexity

The time complexity of the above code is O(N), where N is the number of characters in the given string. But as the number of character maximum can be 32 so the time complexity is almost constant.

The space complexity of the above code is O(1), as we are not using any extra space.

String can be Invalid

In this program, we will check if the current string can be invalid, so we will put two conditions one is to check if the current string may contain any other characters that are not the digits such as the lowercase English characters, uppercase English characters, whitespaces, and special symbols.

Also, we have implemented conditions to check if the current number represented in the string may be out of the range of the integers. So, in that case, we will return the current number is overflowed. Other conditions are same for both the methods.

Example

public class Solution{    
   // creating the function to convert the string to integer 
   public static void atoi(String str){
      int neg = 1; // checking for the negative number         
      if(str.charAt(0) == '-'){
         neg = -1;
      }
      int ans = 0; 
      int i = 0; 
      // if the number is the negative number than start from the next index 
      if(neg  == -1){
         i++;
      }        
      for(; i < str.length(); i++){
         // checking for the base conditions
         // if the current character is not a digit return the invalid answer 
         if(str.charAt(i) < '0' || str.charAt(i) > '9'){
            System.out.println("The given string represents the invalid number");
            return;
         }
         else if( (ans > Integer.MAX_VALUE / 10) || (ans == Integer.MAX_VALUE / 10  && str.charAt(i) - '0' > 7)){
           // overflow condition correct 
           System.out.println("The given string represents the number not in range of integer");
           return;
        }
        ans = ans * 10 + str.charAt(i) - '0';
     }
     ans =  ans* neg;        
     // printing the answer
     System.out.printf("The value of the current number is %d", ans);
   }    
   // main function 
   public static void main(String []args){
      String str = "-354663"; // given string         
      // calling the function 
      atoi(str);
   }
}

Output

The value of the current number is -354663

Time and Space Complexity

The time complexity of the above code is O(N), where N is the number of characters in the given string. But as the number of character maximum can be 32 so the time complexity is almost constant.

The space complexity of the above code is O(1), as we are not using any extra space.

Conclusion

In this tutorial, we have implemented a Java Program to convert the number present in the form of the string to an integer. We have traversed over the string and checked if the current string represents a valid number or not. If the number is not valid we will check for that by using if-else condition for overflow and characters other than digits. The time complexity of the above code is O(N).

Updated on: 11-Jul-2023

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements