Leetcode String to Integer (atoi) problem solution in Java programming

In the Leetcode String to Integer (atoi) problem solution in Java programming Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi function).

The algorithm for myAtoi(string s) is as follows:

Read in and ignore any leading whitespace.
Check if the next character (if not already at the end of the string) is ‘-‘ or ‘+’. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
Convert these digits into an integer (i.e. “123” -> 123, “0032” -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
If the integer is out of the 32-bit signed integer range [-231, 231 – 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 – 1 should be clamped to 231 – 1.
Return the integer as the final result.

Leetcode String to Integer (atoi) problem solution in Java programming

class Solution {
    public int myAtoi(String str) {
        long r=0;
        int i=0;
        if(str.length()==0)
            return 0;
        boolean neg = false;
        while(i<str.length() && str.charAt(i)==' ')
            i++;
        if(i<str.length() && (str.charAt(i)=='+'
          ||str.charAt(i)=='-')) {
            neg = (str.charAt(i)=='-')?true:false;
            i++;
        }
        if(i<str.length() && isDigit(str.charAt(i))) {
             while(i<str.length() && str.charAt(i)=='0')
                 i++;
             while(i<str.length() && isDigit(str.charAt(i)) && r<Integer.MAX_VALUE){
                char c = str.charAt(i);
                r = r*10+(c-48);
                i++;
            }
        }
        if(neg && r>Integer.MAX_VALUE)
            return Integer.MIN_VALUE;
        if(r>Integer.MAX_VALUE)
            return Integer.MAX_VALUE;
        if(neg && r>0)
           r*=-1;
        return (int)r;
    }
    
    public boolean isDigit(char c){
        if(c>=48&&c<=57)
            return true;
        return false;
    }
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *