Implementation of string to integer and myatoi method in Java

Implementation of string to integer and myatoi method in Java

Although this problem is inconsistent with the functions in the API of string to integer, it can exercise the sensitivity of algorithm thinking and the ability to deal with boundary exceptions by adding many additional boundaries or exception handling.

Idea: String questions generally examine the treatment of boundary conditions and special situations. Therefore, when you encounter this problem, you must ask what the input and output should be under various conditions.

Special cases known here are:

Let's start with several groups of test cases:

The correct outputs corresponding to the above test cases are as follows:

The Java implementation code is as follows:

In the above code, the for loop traverses the array to determine whether a character is a number. You can use character IsDigit (c) method. When calculating the result, you can use character Getnumericvalue (c) method gets the value of a character type. In short, it is very convenient to use the static method in character.

The rewritten for loop is as follows:

When asked this question during the interview, we can have a friendly conversation with the interviewer without panic, formulate some rules of the function, that is, how to deal with abnormal input, and then traverse the array to deal with the corresponding exceptions according to the needs~

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>