Title: Implementing a function stringToInt to convert strings into integers. You can't use atoi or other similar library functions.
Basic ideas:
This seems to be a very simple topic, to achieve basic functions, most people can use within 10 lines of code to solve. However, it is not easy to take into account many special cases, i.e. test cases. It is not difficult to solve the problem of numeric conversion itself, but I hope that before writing the code of numeric conversion, the candidate can take into account at least all aspects of test cases such as null pointer, null string","positive and negative sign, overflow, etc., and define reasonable output for these special inputs when writing the code. Of course, these outputs are not necessarily identical to atoi, but they need to be clearly stated and communicated well with the interviewer.
The biggest problem for this candidate is that he has not developed the habit of considering all possible test cases before writing code. The logic is not rigorous enough, so the initial code only deals with the most basic numerical conversion. Later, every time I reminded him of a particular test case, he changed the code. Although he has made two modifications, there are still many obvious loopholes, such as special input empty string ", boundary conditions such as the largest positive integer and the smallest negative integer. Since the idea of this problem is not difficult in itself, I hope that he will consider the problem very possibly thoughtfully and write the code as complete as possible.
Java implementation:
public class StringToInt { public static int stringToInt(String num) { if (num == null || num.length() < 1) { throw new NumberFormatException(num); } char first = num.charAt(0); if (first == '-') { return parseString(num, 1, false); } else if (first == '+') { return parseString(num, 1, true); } else if (first <= '9' && first >= '0') { return parseString(num, 0, true); } else { throw new NumberFormatException(num); } } //Determine whether a character is a number private static boolean isDigit(char c) { return c >= '0' && c <= '9'; } private static int parseString(String num, int index, boolean positive) { if (index >= num.length()) { throw new NumberFormatException(num); } int result; long tmp = 0; while (index < num.length() && isDigit(num.charAt(index))) { tmp = tmp * 10 + num.charAt(index) - '0'; index++; } if (positive) { //The absolute value is not more than 0x7fffffff. if (tmp >= -Integer.MIN_VALUE) { throw new NumberFormatException(num); } else { result = (int) tmp; } } else { //Absolute value not more than 0x80000000 if (tmp >-Integer.MIN_VALUE) { throw new NumberFormatException(num); } else { result = (int) -tmp; } } return result; } }