Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

How can I implement string to java atoi?

Asked by Aashish Chaursiya Oct 10, 2022 951 views 1 answer
Share

About this question

 The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.


The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behaviour of this function.


If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.


If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.


I'm not sure about my checks against integer overflow, but here is my implementation:


public int Atoi(String str) {
    int i = 0;
    while (i < str>        ++i;
    }
    if (i == str.length()) {
        return 0;
    }
    boolean isNegative = false;
    if (str.charAt(i) == '+' || str.charAt(i) == '-') {
        isNegative = str.charAt(i) == '-';
        ++i;
    }
    int result = 0;
    while (i < str>        try {
            result = Math.multiplyExact(result, 10);
            result = Math.addExact(result, Character.getNumericValue(str.charAt(i)));
        } catch (ArithmeticException e) {
            return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }
        ++i;
    }
    if (isNegative) {
        result = -result;
    }
    return result;
}

Your answer

1 Answer

More Java discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Java Blogs

Guides, tips and career advice on Java from JanBask experts.